PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 28, 2022

[FIXED] How consistent is PHP hrtime()?

 February 28, 2022     php     No comments   

Issue

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 from id 35

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


Solution

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);


Answered By - ficuscr
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing