note 124127 added to function.microtime

From: Date: Tue, 20 Aug 2019 02:19:40 +0000
Subject: note 124127 added to function.microtime
Groups: php.notes 
Request: Send a blank email to php-notes+get-211950@lists.php.net to get a copy of this message
As previously pointed out, setting the parameter $get_as_float as true will not allow microseconds precision (what would mean 6 decimal digits). It happens because the float returned has a big integer section, what crops the decimal one leaving it with less than 6 digits. Here is a solution to easily calculate the execution time of a script without having to alter any configuration parameter. It uses the former way of getting microseconds. <?php class Timer { private $timeStart; private $microsecondsStart; private $timeStop; private $microsecondsStop; public function __construct() { $this->start(); } public function start(): void { [$this->microsecondsStart, $this->timeStart] = explode(' ', microtime()); $timeStop = null; $microsecondsStop = null; } public function stop(): void { [$this->microsecondsStop, $this->timeStop] = explode(' ', microtime()); } public function getTime(): float { $timeEnd = $this->timeStop; $microsecondsEnd = $this->microsecondsStop; if (!$timeEnd) { [$microsecondsEnd, $timeEnd] = explode(' ', microtime()); } $seconds = $timeEnd - $this->timeStart; $microseconds = $microsecondsEnd - $this->microsecondsStart; // now the integer section ($seconds) should be small enough // to allow a float with 6 decimal digits return round(($seconds + $microseconds), 6); } } $t = new Timer(); usleep(250); echo $t->getTime(); ?> ---- Server IP: 208.43.231.9 Probable Submitter: 82.199.157.54 (proxied: 2804:14d:90af:4f9b:99c9:6538:7ffc:68b1) ---- Manual Page -- http://php.net/manual/en/function.microtime.php Edit -- https://master.php.net/note/edit/124127 Del: integrated -- https://master.php.net/note/delete/124127/integrated Del: useless -- https://master.php.net/note/delete/124127/useless Del: bad code -- https://master.php.net/note/delete/124127/bad+code Del: spam -- https://master.php.net/note/delete/124127/spam Del: non-english -- https://master.php.net/note/delete/124127/non-english Del: in docs -- https://master.php.net/note/delete/124127/in+docs Del: other reasons-- https://master.php.net/note/delete/124127 Reject -- https://master.php.net/note/reject/124127 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#211950) next »