Приглашаем посетить
Тютчев (tutchev.lit-info.ru)

Using Date and Time for Benchmarks

Previous
Table of Contents
Next

Using Date and Time for Benchmarks

$start = microtimestamp();
$end = microtimestamp();
($end-$start)


Up to now, all date/time functions did not produce results that were more precise than on the second level; no microseconds were available. This changes when you use the function gettimeofday(). This returns an array of values. The key 'sec' returns the associated epoche value; however, 'usec' returns the additional microseconds. With this, a very exact value can be used for operations that need exact measurement, for example, benchmarks.

Benchmarking Code Using microtimestamp() (benchmark.php; excerpt)
<?php
  // ...

  $start = microtimestamp();
  $s = '';
  for ($i=0; $i < 100000; $i++) {
   $s .= "$i";
  }
  $end = microtimestamp();
  echo 'Using double quotes: ' . ($end-$start) .
    '<br />';

  $start = microtimestamp();
  $s = '';
  for ($i=0; $i < 100000; $i++) {
   $s .= $i;
  }
  $end = microtimestamp();
  echo 'Using no quotes: ' . ($end-$start) . '<br
    />';
?>

The code at the beginning of this phrase contains a function microtimestamp() that returns an exact time stamp. This function is called twice; in between, a more or less complex calculation is done. The result of this is a benchmark that might help decide which coding technique is superior.

function microtimestamp() {
  $timeofday = gettimeofday();
  return $timeofday['sec'] + $timeofday['usec'] /
    1000000;
}

Figure 3.3 shows the result. Your mileage might vary, but you will find that using the double quotes just costs time. (In another experiment, you might also find out that it makes no difference whether you use single or double quotesdespite popular beliefs.)

Figure 3.3. The second piece of code is the faster one.

Using Date and Time for Benchmarks



Previous
Table of Contents
Next