Current Location: Home> Latest Articles> Use gettimeofday to get millisecond level time and perform performance testing

Use gettimeofday to get millisecond level time and perform performance testing

gitbox 2025-05-28

1. What is gettimeofday() ?

gettimeofday() is a built-in function in PHP. It returns the current time. The default is an array containing two key parts:

  • sec : The current number of seconds, Unix timestamp.

  • usec : The number of microseconds after the current number of seconds.

Using these two data, we can calculate a more accurate current time.


2. Use gettimeofday() to get millisecond timestamp

The PHP code example is as follows:

<code> <?php // Get the seconds and microseconds of the current time $time = gettimeofday();

// Convert seconds and microseconds to milliseconds
$milliseconds = ($time['sec'] * 1000) + (int)($time['usec'] / 1000);

echo "millisecond timestamp of current time: " . $milliseconds;
?>
</code>

Note here, we multiply the seconds by 1000 to get the milliseconds, then divide the microseconds by 1000 to convert them into milliseconds, and finally add them to get the total millisecond timestamp.


3. Do a simple performance test

In order to verify the accuracy and performance of this timestamp, we can write a performance test to calculate the number of milliseconds used for execution of a piece of code.

Suppose we want to test the execution time of the following loop:

<code> <?php function get_milliseconds() { $time = gettimeofday(); return ($time['sec'] * 1000) + (int)($time['usec'] / 1000); }

// Record the start time
$start = get_milliseconds();

// Execute time-consuming operations, use a loop to simulate it here
for ($i = 0; $i < 1000000; $i++) {
$x = sqrt($i);
}

// Record the end time
$end = get_milliseconds();

echo "Execution time: " . ($end - $start) . " milliseconds";
?>
</code>

In this code, we define a get_milliseconds() function, and use gettimeofday() to get the millisecond timestamp. Then record the time difference before and after execution to obtain the run time.


4. Summary

  • gettimeofday() is a good helper for getting seconds and microseconds time.

  • Through simple calculations, a millisecond time stamp can be obtained.

  • Using millisecond timestamps, relatively accurate performance tests can be performed.

If you need higher precision time, you can consider the hrtime() introduced later in PHP 7.3, which supports nanosecond level.

The above is how to use gettimeofday() to get millisecond time and simple performance testing. I wish you a high-efficiency PHP program!