我正在分析我的PHP網站的性能,並驚訝地發現瓶頸是header
函數。爲什麼header()函數非常慢?
我在PHP 5.3和Apache 2.4上運行。
我爲基準兩個簡單的文件與ab
,發現第一 - 執行phpinfo()
- 是大大低於第二快 - 呼叫header
。
第一個文件(能夠以每秒超過1000個請求運行):(!只能每秒12個的請求)
<?php phpinfo(); ?>
第二個文件:
<?php header('HTTP/1.1 200 OK'); ?>
從完全ab
輸出
C:\work\apache24\bin>ab -n 1000 -c 200 http://q.localhost/test.php
This is ApacheBench, Version 2.3 <$Revision: 1663405 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking q.localhost (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests
Server Software: Apache/2.4.16
Server Hostname: q.localhost
Server Port: 80
Document Path: /test.php
Document Length: 69600 bytes
Server Software: Apache/2.4.16
Server Hostname: q.localhost
Server Port: 80
Document Path: /test.php
Document Length: 69600 bytes
Concurrency Level: 200
Time taken for tests: 0.984 seconds
Complete requests: 1000
Failed requests: 0
Total transferred: 69768000 bytes
HTML transferred: 69600000 bytes
Requests per second: 1015.82 [#/sec] (mean)
Time per request: 196.885 [ms] (mean)
Time per request: 0.984 [ms] (mean, across all concurrent requests)
Transfer rate: 69210.84 [Kbytes/sec] received
完成ab
從第E二次測試:
C:\work\apache24\bin>ab -n 1000 -c 200 http://q.localhost/test.php
This is ApacheBench, Version 2.3 <$Revision: 1663405 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking q.localhost (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests
Server Software: Apache/2.4.16
Server Hostname: q.localhost
Server Port: 80
Document Path: /test.php
Document Length: 0 bytes
Concurrency Level: 200
Time taken for tests: 80.099 seconds
Complete requests: 1000
Failed requests: 0
Total transferred: 168000 bytes
HTML transferred: 0 bytes
Requests per second: 12.48 [#/sec] (mean)
Time per request: 16019.840 [ms] (mean)
Time per request: 80.099 [ms] (mean, across all concurrent requests)
Transfer rate: 2.05 [Kbytes/sec] received
一個簡單的調用header
功能帶來的性能下降到每秒12個請求。這讓我感到震驚。
爲什麼header()
的功能如此之慢,而且有什麼我可以在我的配置中更改以解決它?
非常有趣......我可以在我的(Ubuntu)機器上重現這一點。它不是與身體缺乏產出有關, '<?php echo'foo'; ?>'很快,但是<?php頭('HTTP/1.1 200 OK');回聲'foo'; ?>仍然很慢。 –
如果將以下代碼追加到代碼中,會發生什麼情況? '沖洗(); ob_flush();' – Paolo
@Paolo沒有幫助;根本不會改變結果。 (順便說一下,從邏輯上說,這些刷新應該是相反的,即'ob_flush(); flush()',因爲ob_緩衝區位於寫入緩衝區之前,儘管如此,這也沒有幫助。) –