microtime() - php 日期时间函数
microtime()
(PHP 4, PHP 5, PHP 7)
返回当前 Unix 时间戳和微秒数
说明
microtime([bool $get_as_float]): mixedmicrotime()当前 Unix 时间戳以及微秒数。本函数仅在支持 gettimeofday()系统调用的操作系统下可用。
如果调用时不带可选参数,本函数以"msec sec"的格式返回一个字符串,其中 sec 是自 Unix 纪元(0:00:00 January 1, 1970 GMT)起到现在的秒数,msec 是微秒部分。字符串的两部分都是以秒为单位返回的。
如果给出了$get_as_float参数并且其值等价于TRUE
,microtime()将返回一个浮点数。
Note:$get_as_float参数是 PHP 5.0.0 新加的。
用microtime()对脚本的运行计时
参见time()。
You can use one variable to check execution $time as follow:
Note that the timestamp returned is "with microseconds", not "in microseconds". This is especially good to know if you pass 'true' as the parameter and then calculate the difference between two float values -- the result is already in seconds; it doesn't need to be divided by a million.
All these timing scripts rely on microtime which relies on gettimebyday(2) This can be inaccurate on servers that run ntp to syncronise the servers time. For timing, you should really use clock_gettime(2) with the CLOCK_MONOTONIC flag set. This returns REAL WORLD time, not affected by intentional clock drift. This may seem a bit picky, but I recently saw a server that's clock was an hour out, and they'd set it to 'drift' to the correct time (clock is speeded up until it reaches the correct time) Those sorts of things can make a real impact. Any solutions, seeing as php doesn't have a hook into clock_gettime? More info here: http://tinyurl.com/28vxja9 http://blog.habets.pp.se/2010/09/ gettimeofday-should-never-be-used-to-measure-time
A lot of the comments here suggest adding in the following way: (float)$usec + (float)$sec Make sure you have the float precision high enough as with the default precision of 12, you are only precise to the 0.01 seconds. Set this in you php.ini file. precision = 16
A convenient way to write the current time / microtime as formatted string in your timezone as expression? For the microtime expression only the procedural style can be used. If you do not use namespaces the backslashes may be removed. PHP >= 5.4 needed due to accessing a member of a newly created object in a single expression "(new DateTime())->format('Y-m-d H:i:s.u')" DateTime now is: 2018-06-01 14:54:58 Europe/Berlin Microtime now is: 180601 14:54:58.781716 Europe/Berlin
Need a mini benchmark ? Use microtime with this (very smart) benchmark function : mixed mini_bench_to(array timelist[, return_array=false]) return a mini bench result -the timelist first key must be 'start' -default return a resume string, or array if return_array= true : 'total_time' (ms) in first row details (purcent) in next row example : this example return: ---- string result---- total time : 0.0141 ms start -> init_values : 51.1 % init_values -> loop_fact : 48.9 % ---- tab result---- array ( 'total_time' => 0.0141, 'start -> init_values' => 51.1, 'init_values -> loop_fact' => 48.9, ) The function to include :
Rather than using the list() function, etc. I have found the following code to be a bit cleaner and simpler:
Using microtime() to set 'nonce' value: ini_set("precision", 16); $nonce="nonce=".microtime(true)/0.000001;
While doing some experiments on using microtime()'s output for an entropy generator I found that its microsecond value was always quantified to the nearest hundreds (i.e. the number ends with 00), which affected the randomness of the entropy generator. This output pattern was consistent on three separate machines, running OpenBSD, Mac OS X and Windows. The solution was to instead use gettimeofday()'s output, as its usec value followed no quantifiable pattern on any of the three test platforms.
But note that the default 'precision' setting of PHP* - which is used when a float is converted to a stringy format by echo()ing, casting or json_encode()ing etc - is not enough to hold the six digit accuracy of microtime(true). Out of the box, microtime(true) will echo something like: 1377611450.1234 Which is obviously less than microsecond accuracy. You'll probably want to bump the 'precision' setting up to 16 which will echo something like: 1377611450.123456 *Internally* it will be accurate to the six digits even with the default 'precision', but a lot of things (ie. NoSQL databases) are moving to all-text representations these days so it becomes a bit more important. * 14 at the time of writing
I use this for measure duration of script execution. This function should be defined (and of couse first call made) as soon as possible. However it is true that result depends of gettimeofday() call. ([jamie at bishopston dot net] wrote this & I can confirm) If system time change, result of this function can be unpredictable (much greater or less than zero).
Get date time with milliseconds $micro_date = microtime(); $date_array = explode(" ",$micro_date); $date = date("Y-m-d H:i:s",$date_array[1]); echo "Date: $date:" . $date_array[0]; Test accuracy by running it in a loop.
Of the methods I've seen here, and thought up myself, to convert microtime() output into a numerical value, the microtime_float() one shown in the documentation proper(using explode,list,float,+) is the slowest in terms of runtime. I implemented the various methods, ran each in a tight loop 1,000,000 times, and compared runtimes (and output). I did this 10 times to make sure there wasn't a problem of other things putting a load spike on the server. I'll admit I didn't take into account martijn at vanderlee dot com's comments on testing accuracy, but as I figured the looping code etc would be the same, and this was only meant as a relative comparison, it should not be necessary. The above method took on average 5.7151877 seconds, while a method using substr and simply adding strings with . took on average 3.0144226 seconds. rsalazar at innox dot com dot mx's method using preg_replace used on average 4.1819633 seconds. This shows that there are indeed differences, but for normal use noone is going to notice it. Note that the substr method mentioned isn't quite the one given anonymously below, but one I made based on it: Also worth noting is that the microtime_float() method gets faster, and no less accurate, if the (float) conversions are taken out and the variables are simply added together. Any of the methods that used + or array_sum ended up rounding the result to 2 digits after the decimal point, while (most of) the ones using preg_replace or substr and . kept all the digits. For accurate timing, since floating-point arithmetic would lose precision, I stored microtime results as-is and calculated time difference with this function: For further information, the script itself, etc, see http://edorfaus.xepher.net/div/convert-method-test.php
I like to use bcmath for it
I have been getting negative values substracting a later microtime(true) call from an earlier microtime(true) call on Windows with PHP 5.3.8 Produces negative values ------------------------------ for($i = 0; $i
//Function to convert microtime return to human readable units //функция для конвертации времени, принимает значения в секундах function convert_time($time) { if($time == 0 ){ return 0; } //допустимые единицы измерения $unit=array(-4=>'ps', -3=>'ns',-2=>'mcs',-1=>'ms',0=>'s'); //логарифм времени в сек по основанию 1000 //берем значение не больше 0, т.к. секунды у нас последняя изменяемая по тысяче величина, дальше по 60 $i=min(0,floor(log($time,1000))); //тут делим наше время на число соответствующее единицам измерения т.е. на миллион для секунд, //на тысячу для миллисекунд $t = @round($time/pow(1000,$i) , 1); return $t.$unit[$i]; }
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)