2

Which is faster for something simple such as getting the time from one month ago. I can do:

strtotime('-1 month');

or

mktime(1, 1, 1, date("n") - 1);
  • 3
    Have tried to check this yourself? Is there a particular reason why you care as this is usually a tiny part of any web page request? – Nigel Ren Jan 16 '20 at 15:10

1 Answers1

0

This was tried on Centos 6.10 with PHP 7.1 Running

<?php
set_time_limit(0);
function tester(callable $callback) {
  $times = [];
  for($j = 0; $j < 10; $j++) {
    $time = microtime(true);
    for($i = 0; $i < 100000; $i++) {
      $callback();
    }
    $newTime = microtime(true);
    $times[] = round($newTime - $time, 3).'<br>';
  }
  echo (array_sum($times) / count($times)).'<br>';
}
function stt() {
  strtotime('-1 month');
}
function mt() {
  mktime(1, 1, 1, date("n") - 1);
}
echo 'StrToTime<br>';
tester('stt');
echo 'mktime<br>';
tester('mt');

Results I get:

StrToTime
1.4881
mktime
2.1647

Summary: strtotime is quicker

  • 1
    _strtotime is quicker..._ On how many **different computers with different hardware setups** did you check this? - Which different php versions did you use for that? – B001ᛦ Jan 16 '20 at 14:59
  • [The test labeled "mktime()" was the faster](http://www.spudsdesign.com/benchmark/index.php?t=date5) – B001ᛦ Jan 16 '20 at 15:04
  • On our php7 ubuntu server, the values came out almost the same, negligible difference. Our older* php5 server, the results were leaning to mktime. – IncredibleHat Jan 16 '20 at 15:05