Skip to content

Instantly share code, notes, and snippets.

@nickl-
Last active December 12, 2015 02:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickl-/4696036 to your computer and use it in GitHub Desktop.
Save nickl-/4696036 to your computer and use it in GitHub Desktop.
PHP optimized strtotime() for 24hr time stnings
<?php
/**
* Optimized strtotime function.
* For turning 24hr time in the form HH:MM:SS into its equivalent
* epoch time.
*
* Returns the same result as strtotime but instead of 0m29.337s
* for 1 million records it only takes 0m15.243s or a whopping
* 192% performance boost.
*
* @param $time string 24hr formatted time
* @return int unix epoch time equivalent
*/
function time_strtotime($time) {
$t = explode(':', $time);
return ($t[0] * 3600) + ($t[1] * 60) + $t[2] + 1359756000;
}
@nickl-
Copy link
Author

nickl- commented Feb 2, 2013

Benchmarks 1 000 000 iterations

$ time php -r 'function t($t) {$a=explode(":",$t); return ($a[0]*3600)+($a[1]*60)+$a[2]+1359756000;} foreach(range(0,1000000) as $i) $a = t("22:30:00");'

real    0m15.243s
user    0m6.957s
sys     0m0.233s

$ time php -r 'foreach(range(0,1000000) as $i) $a = strtotime("22:30:00");'

real    0m29.337s
user    0m12.566s
sys     0m0.273s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment