我有一个函数,想要计算总的执行时间。如果执行时间超过10秒,则从函数返回并中断循环。
我有计算执行时间的代码,但不知道如何返回执行时间超过10秒的代码。
for($i=0;$i<5;$i++) {
$time_start = microtime(true);
//call funtion
show(10);
$time_end = microtime(true);
//Total execution time
$total_time = $time_end - $time_start;
echo "Exe Time: ". $total_time;
}
function show() {
sleep(4);
}
发布于 2018-08-02 05:58:43
不幸的是,超时错误不能在php中捕捉到,但是你几乎可以用简单的数学方法& microtime(),
function f(int max_execution_time=10){
$starttime=microtime(true);
//do stuff here
if((microtime(true)-$starttime) > $max_execution_time){
return ETIMEDOUT;
}
//do more stuff here
if((microtime(true)-$starttime) > $max_execution_time){
return ETIMEDOUT;
}
// and more stuff here, and repeat
if((microtime(true)-$starttime) > $max_execution_time){
return ETIMEDOUT;
}
// and finally,
return SUCCESS;
}
只要你看到合适的地方,只要检查它是否应该超时。这不是很准确,因为您不能为大多数函数设置时间限制(例如,如果您的函数正在调用file_get_contents(),您不能为file_get_contents()设置时间限制,除非使用set_time_limit(),但set_time_limit生成的错误无法捕获,并将终止整个php脚本:( )
https://stackoverflow.com/questions/51642730
复制相似问题