PHP开始时间和结束时间问题


PHP begin time and end time issue

class Test extends Controller {    
public function start_process(){  
     $begin_time = time();  
     echo $begin_time ;   // suppose it shows 1318412333
    // statement 1   
    // statement 2   
    // statement 3   
    // statement 4   
    // statement 5   
    // statement 6   
    // some more code
    $this->end_process($begin_time);  
    }
    public function end_process($begin_time){  
    $end_time = time();
    echo $begin_time . " " . $end_time;  
    }
}

现在当我在end_process函数中返回时。假设end_time为1318412390,则得到begin_time与end_time相同。为什么会发生这种情况…如何获得在第一个函数

中设置的原始begin_time

尝试使用microtime。当执行时间小于1秒时,它可以为您提供更准确的时间读取。

编辑

microtime(true);将返回时间为浮点数,因此更容易看到差异。

time();给你秒数,但实际上你处理的是它的分数。正如蜘蛛指出的那样,您需要使用microtime()!

<?php
$start = microtime(true);
// -- do something --
// calulcate duration between $start and now
$duration = microtime(true) - $start;
// print in the format 1.2345 for better reading
printf("took %0.4d seconds", $duration);

我做了一个快速测试:

<?php
ini_set('display_errors', true);
class test {
    public function start_process(){  
        $begin_time = time();  
        echo $begin_time . "<br>";   // suppose it shows 1318412333
        // statement 1   
        // statement 2   
        // statement 3   
        // statement 4   
        // statement 5   
        // statement 6   
        // some more code
        sleep(1);
        $this->end_process($begin_time);  
    }
    public function end_process($begin_time){  
        $end_time = time();
        echo $begin_time . " <br> " . $end_time;  
    }
}
$test = new test();
$test->start_process();
?>
我的结果是
1318415493
1318415493
1318415494

请贴出你的代码

运行下面的代码:

$test = new Test();
    $test->start_process();
    class Test  {    
    public function start_process(){  
         $begin_time = microtime(true);  
         echo $begin_time . ' ';   // suppose it shows 1318412333 
         for($i=0;$i<10000;$i++) { 
           //just some delay as if the script is doing something
         }
        $this->end_process($begin_time);  
        }
        public function end_process($begin_time){  
        $end_time = microtime(true);
        echo $begin_time . " " . $end_time;  
        }
    }

你会看到它可以工作,所以这段代码不是问题。错误一定在代码的其他部分