php 准确测量php脚本执行时间的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6245971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accurate way to measure execution times of php scripts
提问by DomingoSL
I want to know how many milliseconds a PHP for-loop takes to execute.
我想知道执行 PHP for 循环需要多少毫秒。
I know the structure of a generic algorithm, but no idea how to implement it in PHP:
我知道通用算法的结构,但不知道如何在 PHP 中实现它:
Begin
init1 = timer(); // where timer() is the amount of milliseconds from midnight
the loop begin
some code
the loop end
total = timer() - init1;
End
回答by Tim Cooper
You can use the microtime
function for this. From the documentation:
microtime
— Return current Unix timestamp with microsecondsIf
get_as_float
is set toTRUE
, thenmicrotime()
returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.
microtime
— 以微秒为单位返回当前的 Unix 时间戳如果
get_as_float
设置为TRUE
,则microtime()
返回一个浮点数,它表示自 Unix 纪元以来的当前时间,精确到最接近的微秒。
Example usage:
用法示例:
$start = microtime(true);
while (...) {
}
$time_elapsed_secs = microtime(true) - $start;
回答by Aditya P Bhatt
You can use microtime(true)
with following manners:
您可以microtime(true)
通过以下方式使用:
Put this at the start of your php file:
把它放在你的 php 文件的开头:
//place this before any script you want to calculate time
$time_start = microtime(true);
// your script code goes here
// 你的脚本代码放在这里
// do something
Put this at the end of your php file:
把它放在你的php文件的末尾:
// Display Script End time
$time_end = microtime(true);
//dividing with 60 will give the execution time in minutes other wise seconds
$execution_time = ($time_end - $time_start)/60;
//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';
It will output you result in minutes
.
它会输出你的结果minutes
。
回答by Iwazaru
You can use REQUEST_TIME
from the $_SERVER
superglobal array. From the documentation:
您可以REQUEST_TIME
从$_SERVER
超全局数组中使用。从文档:
REQUEST_TIME
The timestamp of the start of the request. (Available since PHP 5.1.0.)
REQUEST_TIME_FLOAT
The timestamp of the start of the request, with microsecond precision. (Available since PHP 5.4.0.)
REQUEST_TIME
请求开始的时间戳。(自 PHP 5.1.0 起可用。)
REQUEST_TIME_FLOAT
请求开始的时间戳,精度为微秒。(自 PHP 5.4.0 起可用。)
This way you don't need to save a timestamp at the beginning of your script. You can simply do:
这样您就不需要在脚本的开头保存时间戳。你可以简单地做:
<?php
// Do stuff
usleep(mt_rand(100, 10000));
// At the end of your script
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
echo "Did stuff in $time seconds\n";
?>
Here, $time
would contain the time elapsed since the start of the script in seconds, with microseconds precision (eg. 1.341
for 1 second and 341 microseconds)
在这里,$time
将包含自脚本启动以来经过的时间(以秒为单位),精度1.341
为微秒(例如,1 秒和 341 微秒)
More info:
更多信息:
PHP documentation: $_SERVER
variablesand microtime
function
PHP 文档: $_SERVER
变量和microtime
函数
回答by Solo Omsarashvili
Create file loadtime.php
创建文件 loadtime.php
<?php
class loadTime{
private $time_start = 0;
private $time_end = 0;
private $time = 0;
public function __construct(){
$this->time_start= microtime(true);
}
public function __destruct(){
$this->time_end = microtime(true);
$this->time = $this->time_end - $this->time_start;
echo "Loaded in $this->time seconds\n";
}
}
Than in the beggining of your script, after <?php
write include 'loadtime.php'; $loadtime=new loadTime();
比在你的剧本的开头,<?php
写完之后include 'loadtime.php'; $loadtime=new loadTime();
When page is loaded at the end there will be written "Loaded in x seconds"
当页面在最后加载时,会写成“在 x 秒内加载”
回答by Dvir Azulay
$start = microtime(true);
for ($i = 0; $i < 10000; ++$i) {
// do something
}
$total = microtime(true) - $start;
echo $total;
回答by patapizza
See microtime().
请参阅microtime()。
回答by flaviovs
Here is a function that times execution of any piece of PHP code, much like Python's timeit module does: https://gist.github.com/flaviovs/35aab0e85852e548a60a
这是一个对任何 PHP 代码段执行计时的函数,很像 Python 的 timeit 模块:https: //gist.github.com/flaviovs/35aab0e85852e548a60a
How to use it:
如何使用它:
include('timeit.php');
const SOME_CODE = '
strlen("foo bar");
';
$t = timeit(SOME_CODE);
print "$t[0] loops; $t[2] per loop\n";
Result:
结果:
$ php x.php
100000 loops; 18.08us per loop
Disclaimer: I am the author of this Gist
免责声明:我是这个要点的作者
EDIT: timeit is now a separate, self-contained project at https://github.com/flaviovs/timeit
编辑:timeit 现在是https://github.com/flaviovs/timeit 上的一个独立的自包含项目
回答by wallyk
You have the right idea, except a more precise timing is available with the microtime()function.
您的想法是正确的,除了microtime()函数可以提供更精确的计时。
If what is inside the loop is fast, it is possible that the apparent elapsed time will be zero. If so, wrap another loop around the code and call it repeatedly. Be sure to divide the difference by the number of iterations to get a per-once time. I have profiled code which required 10,000,000 iterations to get consistent, reliable timing results.
如果循环内的内容很快,则表观经过的时间可能为零。如果是这样,请在代码周围环绕另一个循环并重复调用它。请务必将差异除以迭代次数以获得每次时间。我分析了需要 10,000,000 次迭代才能获得一致、可靠的计时结果的代码。
回答by azoundria
I thought I'd share the function I put together. Hopefully it can save you time.
我想我会分享我放在一起的功能。希望它可以节省您的时间。
It was originally used to track timing of a text-based script, so the output is in text form. But you can easily modify it to HTML if you prefer.
它最初用于跟踪基于文本的脚本的计时,因此输出为文本形式。但是,如果您愿意,您可以轻松地将其修改为 HTML。
It will do all the calculations for you for how much time has been spent since the start of the script and in each step. It formats all the output with 3 decimals of precision. (Down to milliseconds.)
它将为您计算自脚本启动以来以及在每个步骤中花费的时间。它将所有输出格式化为 3 位小数精度。(低至毫秒。)
Once you copy it to the top of your script, all you do is put the recordTime function calls after each piece you want to time.
将它复制到脚本的顶部后,您要做的就是将 recordTime 函数调用放在您想要计时的每个片段之后。
Copy this to the top of your script file:
将此复制到脚本文件的顶部:
$tRecordStart = microtime(true);
header("Content-Type: text/plain");
recordTime("Start");
function recordTime ($sName) {
global $tRecordStart;
static $tStartQ;
$tS = microtime(true);
$tElapsedSecs = $tS - $tRecordStart;
$tElapsedSecsQ = $tS - $tStartQ;
$sElapsedSecs = str_pad(number_format($tElapsedSecs, 3), 10, " ", STR_PAD_LEFT);
$sElapsedSecsQ = number_format($tElapsedSecsQ, 3);
echo "//".$sElapsedSecs." - ".$sName;
if (!empty($tStartQ)) echo " In ".$sElapsedSecsQ."s";
echo "\n";
$tStartQ = $tS;
}
To track the time that passes, just do:
要跟踪经过的时间,只需执行以下操作:
recordTime("What We Just Did")
For example:
例如:
recordTime("Something Else")
//Do really long operation.
recordTime("Really Long Operation")
//Do a short operation.
recordTime("A Short Operation")
//In a while loop.
for ($i = 0; $i < 300; $i ++) {
recordTime("Loop Cycle ".$i)
}
Gives output like this:
给出这样的输出:
// 0.000 - Start
// 0.001 - Something Else In 0.001s
// 10.779 - Really Long Operation In 10.778s
// 11.986 - A Short Operation In 1.207s
// 11.987 - Loop Cycle 0 In 0.001s
// 11.987 - Loop Cycle 1 In 0.000s
...
// 12.007 - Loop Cycle 299 In 0.000s
Hope this helps someone!
希望这可以帮助某人!
回答by Eugene Kaurov
if you like to display that time in seconds:
如果您想以秒为单位显示该时间:
<?php
class debugTimer
{
private $startTime;
private $callsCounter;
function __construct()
{
$this->startTime = microtime(true);
$this->callsCounter = 0;
}
public function getTimer(): float
{
$timeEnd = microtime(true);
$time = $timeEnd - $this->startTime;
$this->callsCounter++;
return $time;
}
public function getCallsNumer(): int
{
return $this->callsCounter;
}
}
$timer = new debugTimer();
usleep(100);
echo '<br />\n
'.$timer->getTimer(). ' seconds before call #'.$timer->getCallsNumer();
usleep(100);
echo '<br />\n
'.$timer->getTimer(). ' seconds before call #'.$timer->getCallsNumer();