How to subtract microtime and display date with milliseconds in php?

别来无恙 提交于 2019-11-28 11:04:23

You need to use microtime for the start/end values, and only format it for display at the end.

// Get the start time in microseconds, as a float value
$starttime = microtime(true);

/************/
/* Do stuff */
/************/

// Get the difference between start and end in microseconds, as a float value
$diff = microtime(true) - $starttime;

// Break the difference into seconds and microseconds
$sec = intval($diff);
$micro = $diff - $sec;

// Format the result as you want it
// $final will contain something like "00:00:02.452"
$final = strftime('%T', mktime(0, 0, $sec)) . str_replace('0.', '.', sprintf('%.3f', $micro));

Note: this is returning float values from microtime and using float arithmetic to simplify the math, so your numbers may be extremely slightly off due to the float rounding problem, but you are rounding the result to 3 digits in the end anyway, and minor fluctuations in processor timing are greater than floating point errors anyway, so this is not problem for you on multiple levels.

Well phpmyadmin uses this a code like this to calculate the time that a query took. It's similar to your requirements:

//time before
list($usec, $sec) = explode(' ',microtime($starttime));
$querytime_before = ((float)$usec + (float)$sec);
/* your code */

//time after
list($usec, $sec) = explode(' ',microtime($endtime));
$querytime_after = ((float)$usec + (float)$sec);
$querytime = $querytime_after - $querytime_before;

I think this should work for you. You just have to figure your output format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!