在对PHP脚本进行概要分析后,我发现创建异常似乎需要大量时间:
%Time Real User System Calls secs/call Name 100.0 0.00 3448.05 0.00 8.89 0.00 1.81 1 0.0000 3448.0543 main 64.7 2230.28 2230.28 0.02 0.02 0.00 0.00 892 2.5003 2.5003 sleep 35.1 0.01 1211.84 0.00 8.16 0.00 1.49 1001 0.0000 1.2106 do_process 34.7 986.81 1197.34 2.59 2.60 1.18 1.18 1330 0.7420 0.9003 file_get_contents 6.1 0.00 210.53 0.00 0.01 0.00 0.01 28 0.0000 7.5191 __lambda_func 6.1 210.53 210.53 0.01 0.01 0.01 0.01 28 7.5191 7.5191 ErrorException->__construct 0.4 0.00 13.47 0.01 5.21 0.00 0.18 206 0.0000 0.0654 do_check 0.4 13.15 13.15 5.08 5.08 0.15 0.15 402 0.0327 0.0327 preg_replace
因此,每个
ErrorException->__construct
的实际(不是CPU)时间为7.5秒。 我正在寻找有关改进方法的想法! 相关代码:
set_error_handler( create_function( '$severity, $message, $file, $line', 'throw new ErrorException($message, $severity, $severity, $file, $line);' ) ); $opts = array( 'http' => array( 'method' => 'GET', 'timeout' => 60 ) ); $ctx = stream_context_create($opts); try { $this->data = file_get_contents($url, false, $ctx); } catch (Exception $e) { # The set_error_handler call ensures that we arrive here on any type # of error. $this->data = ''; if(preg_match('/HTTP\/1.[0|1] 4[0-9][0-9] /', $e->getMessage()) == 1) { return 404; } else if(strpos($e->getMessage(), "php_network_getaddresses: getaddrinfo failed") !== false) { return 1000; } else { $this->message = $e->getMessage(); return -1; } }
即使没有明显的答案,我也想了解哪些因素可能会影响实时性如此之大。我的理解是,构造函数不包括
file_get_contents
调用本身或catch
子句的时间,因此无法真正想到一个很好的理由(除了尝试分配大量内存之外),为什么这样做应该很慢。
最佳答案
您正在使用通过调用create_function()
创建的oldschool lambda函数。是否有一个原因?因为该函数的运行方式很慢。您使用函数代码向其传递了STRING,但是必须在运行时评估该字符串。操作码缓存无法为您缓存该代码。
关于php - PHP ErrorException创建需要很长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18682239/