dougan1330 2015-10-13 15:51
浏览 31
已采纳

PHP microtime()是正确的吗?

I have used microtime() to check code execution time. But it seems very strange like time tracked is not correct.

So in my test.php, I have code like following:

$debug = true; 
$start = microtime(true); 
$newline = "<br/>";

...

if ($debug) {
    $time_elapsed_secs = microtime(true) - $start;
    $start = microtime(true);
    echo 'Step 1 Done: ' . $time_elapsed_secs . $newline; }

...

if ($debug) {
    $time_elapsed_secs = microtime(true) - $start;
    $start = microtime(true);
    echo 'Step 2 Done: ' . $time_elapsed_secs . $newline; }

Then when I open the URL on browser, it response in less then 1 sec, but it shows something strange value like Step 1 Done: 0.0026565 Step 2 Done: 9.8646454

How come this would happen? Do I do something in wrong way?

  • 写回答

2条回答 默认 最新

  • duanmo5724 2015-10-13 17:37
    关注

    I'm guessing you left a tiny detail out of your description. I think the output you actually saw was more like...

    Step 1 Done: 0.0026565
    ...
    Step 2 Done: 9.8646454E-5
    

    PHP will put floats into scientific notation when they are lower than 0.0001. To make things consistent to read in your output, try changing your code to the following to display the microtimes in decimal notation.

    $debug = true; 
    $start = microtime(true); 
    $newline = "<br/>";
    
    usleep(30);
    
    if ($debug) {
        $time_elapsed_secs = microtime(true) - $start;
        $start = microtime(true);
        echo 'Step 1 Done: ' . sprintf( '%f', $time_elapsed_secs ) . $newline; }
    
    usleep(1);
    
    if ($debug) {
        $time_elapsed_secs = microtime(true) - $start;
        $start = microtime(true);
        echo 'Step 2 Done: ' . sprintf( '%f', $time_elapsed_secs ) . $newline; }
    

    [Note: added usleep() calls to show something happening.]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等