Now let's take a look at another method to test the script running time-use the benchmark_timer class to test the time consumed by code execution and the time between each call and the next call in the code.
Benchmark2.php
require_once
'Benchmark/Timer.php'
;
$timer
= new
Benchmark_Timer
();
$timer
->
start
();
$timer
->
setMarker
(
'start_myFunction'
);
for(
$i
=
0
;
$i
<
10
;
$i
++){
myFunction
(
$argument
);
}
$timer
->
setMarker
(
'end_myFunction'
);
$timer
->
stop
();
$profiling
=
$timer
->
getProfiling
();
echo
'
Time elapsed: '
.
$timer
->
timeElapsed
(
'start_myFunction'
,
'end_myFunction'
) .
'
';
echo
'
'
;
print_r
(
$profiling
);
echo
''
;
exit;
function
myFunction
(
$var
) {
static
$counter
=
0
;
// do something
echo
$counter
++ .
' '
;
}
?>
First, create a benchmark timer object $ timer. Call the START () method to start timing. The setmaker () method is used to mark the code segment to be tested. The myfunction () function is called in a loop to indicate the code to be executed (of course, it is not that simple in practice ). Then, use the setmarker () method of the $ timer object to mark the end point of the program execution. Getprofiling () is used to obtain the analysis information. The time consumed by program execution between two tags is calculated using the timeelapsed () method (like the loop in the example ). Finally, use print_r () to output the information to the screen:
0 1 2 3 4 5 6 7 8 9
Time elapsed: 0.000594
Array
(
[0] => Array
(
[name] => Start
[time] => 1085730111.27175200
[diff] => -
[total] => 1085730111.271752
)
[1] => Array
(
[name] => start_myFunction
[time] => 1085730111.27203800
[diff] => 0.000286
[total] => 1085730111.272038
)
[2] => Array
(
[name] => end_myFunction
[time] => 1085730111.27263200
[diff] => 0.000594
[total] => 1085730111.272632
)
[3] => Array
(
[name] => Stop
[time] => 1085730111.27271800
[diff] => 0.000086
[total] => 1085730111.272718
)
)
In this way, you can set a large number of time period tags in the code to obtain the time consumed during code execution, it is easy to see which part of the code affects the running efficiency of the entire program. Then begin to improve this part of the code.
With the above two methods, you can find out some of the Code that most affects the speed. It can also be used to test the optimized code to see how fast the execution speed has been improved. Test-> Optimization-> test-> optimization... In this way, you can finally determine the code that provides the best efficiency.