Skip to content

Instantly share code, notes, and snippets.

@ahwayakchih
Created July 6, 2011 11:51
Show Gist options
  • Save ahwayakchih/1067053 to your computer and use it in GitHub Desktop.
Save ahwayakchih/1067053 to your computer and use it in GitHub Desktop.
Test PHP `DateTime(date())` vs `if(can call DateTime->setTimestamp) DateTime->setTimestamp() else DateTime(date())`
<?php
/*
* Test how calling `DateTime(date())` compares to checking for `DateTime::createFromFormat()`
* or `DateTime->setTimestamp()` and using `date()` as fallback only.
*
* Output should show something like:
*
* Using date() without any check: 4.3791408538818s
* Using DateTime::createFromFormat(): 5.6960089206696s
* Using DateTime->setTimestamp(): 3.3501291275024s
*
*/
$string = time();
// Benchmark code without function check
$start = microtime(true);
for ($i = 100000; $i > 0; $i--) {
if (is_numeric($string)) {
$date = new DateTime(date(DateTime::ISO8601, $string));
}
}
$end = microtime(true) - $start;
echo "Using date() without any check: {$end}s\n";
// Benchmark code that checks if method exists
$start = microtime(true);
for ($i = 100000; $i > 0; $i--) {
if(is_numeric($string)) {
if (method_exists('DateTime', 'createFromFormat')) {
$date = DateTime::createFromFormat('U', $string);
}
else {
$date = new DateTime(date(DateTime::ISO8601, $string));
}
}
}
$end = microtime(true) - $start;
echo "Using DateTime::createFromFormat(): {$end}s\n";
// Benchmark code that checks if method exists
$start = microtime(true);
for ($i = 100000; $i > 0; $i--) {
if(is_numeric($string)) {
if (method_exists('DateTime', 'setTimestamp')) {
$date = new DateTime();
$date->setTimestamp($string);
}
else {
$date = new DateTime(date(DateTime::ISO8601, $string));
}
}
}
$end = microtime(true) - $start;
echo "Using DateTime->setTimestamp(): {$end}s\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment