Skip to content

Instantly share code, notes, and snippets.

@KingCrunch
Last active Jan 12, 2018
Embed
What would you like to do?
$ php some-bench.php
strtotime: 0.15609812736511
datetime: 0.31521701812744
datetime without instanciation: 0.11794400215149
custom: 0.70522284507751
<?php
// See https://en.code-bude.net/2013/12/19/benchmark-strtotime-vs-datetime-vs-gettimestamp-in-php/
$start = microtime(true);
for ($i = 0; $i < 100000; $i ++) {
$a=strtotime("2012-05-28");
}
echo "strtotime: ", (microtime(true) - $start), "\n";
$start = microtime(true);
for ($i = 0; $i < 100000; $i ++) {
$date=new DateTime("2012-05-28");
$a = $date->getTimestamp();
}
echo "datetime: ", (microtime(true) - $start), "\n";
$date=new DateTime("2012-05-28");
$start = microtime(true);
for ($i = 0; $i < 100000; $i ++) {
$a = $date->getTimestamp();
}
echo "datetime without instanciation: ", (microtime(true) - $start), "\n";
$start = microtime(true);
for ($i = 0; $i < 100000; $i ++) {
$a = getTimestamp("2012-05-28");
}
echo "custom: ", (microtime(true) - $start) , "\n";
function getTimestamp($timeStr)
{
$daysInMonth = array(0,31,59,90,120,151,181,212,243,273,304,334);
$dateArr = explode("-", $timeStr);
//Add years to the day of the year entered
$days = ($dateArr[0]-1970) * 365;
//Add leap years, days
for ($i = 1972; $i <= $dateArr[0]; $i+=4)
{
if (($i%4==0 && $i%100 != 0) || $i%400==0)
$days++;
}
//Days until 31.03. of the year
$daysTimeswitch = $days + 90;
//Determine day of the week using MOD 3 . (+3 because 01.01.1970 = Thursday)
//Pull off day of the week from 31. = last Sunday of the month => Daylight saving time
$daySummertime = 31 - ((($daysTimeswitch%7) + 3)%7);
$daysTimeswitch = $days + 304;
$dayWintertime = 31 - ((($daysTimeswitch%7) + 3)%7);
if (($dateArr[1] > 3 && $dateArr[1] < 10)
|| ($dateArr[1] == 3 && $dateArr[2] > $daySummertime)
|| ($dateArr[1] == 10 && $dateArr[2] <= $dayWintertime))
{
$summerWinterTime = 3600;
}
else{
$summerWinterTime = 0;
}
//Pull off leap year day
$days -= (($dateArr[0]%4==0 && $dateArr[0]%100 != 0) || $dateArr[0]%400==0) ? ($dateArr[1] > 2) ? 0 : 1 : 0;
//Add days to months of the current year
$days += $daysInMonth[$dateArr[1]-1];
//Add days of the current year
$days += $dateArr[2] - 1;
//Pull off 3600 seconds for time shift. (Unix timestamp / UTC)
return $days * 86400 - 3600 - $summerWinterTime;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment