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;
}
}
Now when i echo in end_p开发者_如何学运维rocess function . Suppose end_time is 1318412390 i get begin_time same as end_time. Why does this happen.. How do get the original begin_time which was set in first function
Try using microtime. It gives you a more accurate time reading for when execution time is less than a second.
Edit
microtime(true);
will return the time as a float so it's easier to see the difference.
time(); gives you seconds, but what you're actually dealing with is fractions thereof. As spider pointed out, you want to go with 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);
I did a quick test:
<?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();
?>
My result is
1318415493
1318415493
1318415494
Please post your code.
Just run this code:
$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;
}
}
You'll see that is works, so that piece of code isn't the problem. The error must be in some other part of the code.
精彩评论