gettimeofday() is a built-in function in PHP that returns details of the current time, including seconds and microseconds. Its return value is an array containing the following keys:
sec : The number of seconds of the current time (calculated from the Unix epoch)
usec : the number of microseconds in the current second
Through these two values, we can get a more accurate timestamp than time() or microtime() , which is suitable for high-precision performance testing.
The basic idea is: record the time difference before and after the code is executed, and calculate the execution time.
<?php
// Record the start time
$start = gettimeofday();
// Here is the code you want to test
usleep(500000); // Analog delay 0.5 Second
// Record the end time
$end = gettimeofday();
// Calculate the time difference,单位为Second(含微Second)
$duration = ($end['sec'] - $start['sec']) + ($end['usec'] - $start['usec']) / 1000000;
echo "Code execution time:{$duration} Second";
?>
In the above code:
gettimeofday() returns an associative array.
We calculate the difference in seconds and the difference in microseconds respectively, and then convert it into seconds.
The final $duration is a floating point number that represents the exact number of seconds the code is running.
Suppose we want to test the performance of a function:
<?php
function testFunction() {
$sum = 0;
for ($i = 0; $i < 1000000; $i++) {
$sum += $i;
}
return $sum;
}
$start = gettimeofday();
$result = testFunction();
$end = gettimeofday();
$duration = ($end['sec'] - $start['sec']) + ($end['usec'] - $start['usec']) / 1000000;
echo "Function execution result:$result\n";
echo "Execution time:{$duration} Second\n";
?>
In this example, we measure the time when the testFunction() function is executed to facilitate us to evaluate the function performance.
High precision : microsecond-level time measurement, more accurate than time() .
Simple and easy to use : the return value is an array, and the information of seconds and microseconds is clear.
No dependency : PHP built-in functions, no extensions are required.
The time returned by gettimeofday() is the current time of the server, which may be affected by system time adjustments, and is not suitable for cross-server or distributed time comparisons.
For very short code segments, the execution time can be very small, and it is recommended to run multiple times and calculate the average value for more stable results.