I'm currently using hrtime()
in one of my project, a chat system (still in development stage).
On each message sent, I store the hrtime(true)
value along with the message into database.
So recipient will request for new messages based on last message hrtime stored in app localStorage.
like for example: select*from messages_table where message_hrtime>$last_hrtime and message_to=$me
It has been working alright until today, thrn I noticed new messages
hrtime(true)
value inserted into DB decreased which make new messages not to be received.
Notice the column message_hrtime decreased on id 35
And according to this article https://thephp.cc/articles/high-resolution-monotonic-timer, that hrtime() is ever increasing.
Now confused if the hrtime(true)
is consistent.
PHP 7.3
CodePudding user response:
Where microtime provides "the current Unix timestamp with microseconds", The HRTime class, or High resolution timing, "Returns the system's high resolution time, counted from an arbitrary point in time. The delivered timestamp is monotonic and can not be adjusted.".
That means HRTime is independent of server time. You can't depend on this across servers or even across restarts of a server. I wouldn't trust it across code execution. Use the database timestamp or simply switch to use PHP's microtime
.
HRTime has interesting application as a precise stop watch as shown here on php.net: https://www.php.net/manual/en/hrtime.example.basic.php
<?php
$c = new HRTime\StopWatch;
$c->start();
/* measure this code block execution */
for ($i = 0; $i < 1024*1024; $i );
$c->stop();
$elapsed0 = $c->getLastElapsedTime(HRTime\Unit::NANOSECOND);
/* measurement is not running here*/
for ($i = 0; $i < 1024*1024; $i );
$c->start();
/* measure this code block execution */
for ($i = 0; $i < 1024*1024; $i );
$c->stop();
$elapsed1 = $c->getLastElapsedTime(HRTime\Unit::NANOSECOND);
$elapsed_total = $c->getElapsedTime(HRTime\Unit::NANOSECOND);