Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

thebigk's avatar
Level 13

PHP: Calculate time difference in seconds and milliseconds with hrtime()?

How do I calculate the time difference in seconds, milliseconds and microseconds from the two timestamps obtained using hrtime() function in PHP 7.3?

I've the following code and want to figure out the exact time required for execution in seconds and milliseconds.

$start_time = hrtime(true);

for($i=1; $i <= 10000; $i++) {
    //do something
}

$end_time = hrtime(true);

dd($end_time - $start_time);

I'm not sure what exactly does the obtained result represent. On my test run, I received 553357183 but not sure if it's in milliseconds or nanoseconds.

PS: I've run this on MacOS running php7.3 and I need the number on my Live server that runs uBuntu 18 with php 7.3.

Can someone help?

0 likes
6 replies
Cronix's avatar
Cronix
Best Answer
Level 67

According to the manual for hrtime(): https://www.php.net/manual/en/function.hrtime.php

Returns an array of integers in the form [seconds, nanoseconds], if the parameter get_as_number is false. Otherwise the nanoseconds are returned as integer (64bit platforms) or float (32bit platforms).

If you pass true, then it returns only nanoseconds

thebigk's avatar
Level 13

Thank you, @cronix . If I've to get the difference in human readable seconds, would this be the right way to do it

($end_time - $start_time) / 1e9

OR

($end_time - $start_time) / 1e-9 ?

Cronix's avatar

If you want it in seconds, why pass true and only get ns? If you don't, it returns an array with the first number being seconds and the second number being ns

thebigk's avatar
Level 13

@cronix - I got confused with the [seconds,nanoseconds] part. If I don't pass true, do I only get the nanoseconds part or the combined value of seconds + nanoseconds?

That is, if my total time of execution is more than one second; will the returned number (with true) represent total number of nanoseconds since I started the counter OR only the nanoseconds passed AFTER the initial full second?

thebigk's avatar
Level 13

Update: I tried adding sleep() to the code; and it "looks like" the function returns summation of seconds + nanoseconds. How can I be confirm this?

Cronix's avatar

Did you read the docs? It tells exactly what the parameters are, and what the output is for different parameters. I quoted it as well.

1 like

Please or to participate in this conversation.