Start and stop a timer PHP

前端 未结 8 728
北海茫月
北海茫月 2020-11-30 08:08

I need some information regarding starting and stopping a timer in PHP. I need to measure the elapsed time from the start of my .exe program (I\'m using exec()

相关标签:
8条回答
  • 2020-11-30 09:01
    class Timer
    {
        private $startTime = null;
    
        public function __construct($showSeconds = true)
        {
            $this->startTime = microtime(true);
            echo 'Working - please wait...' . PHP_EOL;
        }
    
        public function __destruct()
        {
            $endTime = microtime(true);
            $time = $endTime - $this->startTime;
    
            $hours = (int)($time / 60 / 60);
            $minutes = (int)($time / 60) - $hours * 60;
            $seconds = (int)$time - $hours * 60 * 60 - $minutes * 60;
            $timeShow = ($hours == 0 ? "00" : $hours) . ":" . ($minutes == 0 ? "00" : ($minutes < 10 ? "0" . $minutes : $minutes)) . ":" . ($seconds == 0 ? "00" : ($seconds < 10 ? "0" . $seconds : $seconds));
    
            echo 'Job finished in ' . $timeShow . PHP_EOL;
        }
    }
    
    $t = new Timer(); // echoes "Working, please wait.."
    
    [some operations]
    
    unset($t);  // echoes "Job finished in h:m:s"
    
    0 讨论(0)
  • 2020-11-30 09:06

    Since PHP 7.3 the hrtime function should be used for any timing.

    $start = hrtime(true);
    // execute...
    $end = hrtime(true);   
    
    echo ($end - $start);                // Nanoseconds
    echo ($end - $start) / 1000000000;   // Seconds
    

    The mentioned microtime function relies on the system clock. Which can be modified e.g. by the ntpd program on ubuntu or just the sysadmin.

    0 讨论(0)
提交回复
热议问题