###1. php5.3 以上版本(必須是線程安全),使用php_pthreads擴展,可使php真正地支持多線程。 ###2. 下載安裝php
###3. 測試代碼 使用多線程平均時間:8.5S, 使用foreach循環平均時間:22.0Shtml
<!-- lang: php --> <?php //多線程測試 class myThread extends Thread{ public $url = null; public $data = null; public function __construct($url){ $this->url = $url; } public function run(){ $this->data = model_http_curl_get($this->url); $file = './pic/' . md5($this->url) . '.html'; file_put_contents($file, $this->data); } } function getByThread($urls){ $thread_array = array(); foreach ($urls as $key => $value){ $thread_array[$key] = new myThread($value["url"]); $thread_array[$key]->start(); } } function getByforeach($urls){ foreach($urls as $key=>$value){ echo $key; $data = model_http_curl_get($value["url"]); $file = './pic/' . $key . '.html'; file_put_contents($file, $data); } } function model_http_curl_get($url,$userAgent=""){ $userAgent = $userAgent ? $userAgent : 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_TIMEOUT, 5); curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); $result = curl_exec($curl); curl_close($curl); return $result; } //開始測試 $urls_array = array(); for ($i=1; $i <= 30; $i++){ //$urls_array[] = array("url" => "http://www.baidu.com/s?wd=".mt_rand(10000,20000)); $urls_array[] = array("url" => "http://tu.duowan.com/gallery/86760.html#p". $i); } //多線程 getByThread($urls_array); //foreahc循環 - 平均 22.0s //getByforeach($urls_array); ?>