首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何检查函数执行时间,如果超过10秒则返回

如何检查函数执行时间,如果超过10秒则返回
EN

Stack Overflow用户
提问于 2018-08-02 05:49:25
回答 1查看 242关注 0票数 1

我有一个函数,想要计算总的执行时间。如果执行时间超过10秒,则从函数返回并中断循环。

我有计算执行时间的代码,但不知道如何返回执行时间超过10秒的代码。

代码语言:javascript
复制
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);
}
EN

回答 1

Stack Overflow用户

发布于 2018-08-02 05:58:43

不幸的是,超时错误不能在php中捕捉到,但是你几乎可以用简单的数学方法& microtime(),

代码语言:javascript
复制
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脚本:( )

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51642730

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档