1
我希望你能帮助我优化和加快我编写的脚本来检索多个数据源的数据。现在脚本通常需要2到10分钟才能运行,具体取决于一天的时间。并行运行多个POST请求,改进和优化脚本的速度。多线程可能吗?
所有和任何帮助将非常赞赏。
解释脚本:
我使用foreach循环通过五种不同的URL来运行,那么每个URL都会有与所得到的数据被写入到文件中进行了五次POST请求。
什么,我希望:
为了提高我希望有可能让每个独立的职能范围内的五个网址,并再运行相互平行的五大功能脚本的速度。
我读过的其中一个选项是pcntl_fork,可以用它来实现我所需要的吗?如果不是,还有其他选择吗?
我的脚本:
foreach($urls as $url){
$firmato = file_get_html($url, false, stream_context_create($firmato_request));
if (preg_match('(record totali ([\d]+))', $firmato, $count)) {
$firmato_count = $count[1];
};
$inviato = file_get_html($url, false, stream_context_create($inviato_request));
if (preg_match('(record totali ([\d]+))', $inviato, $count)) {
$inviato_count = $count[1];
};
$positive = file_get_html($url, false, stream_context_create($positive_request));
if (preg_match('(record totali ([\d]+))', $positive, $count)) {
$positive_count = $count[1];
};
$negative = file_get_html($url, false, stream_context_create($negative_request));
if (preg_match('(record totali ([\d]+))', $negative, $count)) {
$negative_count = $count[1];
};
$total = file_get_html($url, false, stream_context_create($default_request));
if (preg_match('(record totali ([\d]+))', $total, $count)) {
$default_count = $count[1];
$other_count = $firmato_count+$inviato_count+$positive_count+$negative_count-$default_count;
};
if ($url == 'http://sourceOne.com/MessageServlet') {
$cacheDir = 'cache/one/';
} elseif ($url == 'http://sourceTwo.com/MessageServlet') {
$cacheDir = 'cache/two/';
} elseif ($url == 'http://sourceThree.com/MessageServlet') {
$cacheDir = 'cache/three/';
} elseif ($url == 'http://sourceFour.com/MessageServlet') {
$cacheDir = 'cache/four/';
} elseif ($url == 'http://sourceFive.com/MessageServlet') {
$cacheDir = 'cache/five/';
}
$cache_file = $cacheDir.'hour_'.sprintf('%02d', $previousHour).'.txt';
$data = '<tr><td>'.sprintf('%02d', $previousHour).':00</td><td>'.$firmato_count.'</td><td>'.$inviato_count.'</td><td>'.$positive_count.'</td><td>'.$negative_count.'</td><td>'.$other_count.'</tr>';
file_put_contents($cache_file, $data);
};
您将在这里找到一些关于PHP中多线程的好答案:http://stackoverflow.com/questions/70855/how-can-one-use-multi-threading-in-php-applications – Oliver
事实上,有你的问题有太多可能的答案。例如。你可以使用curl,比file_get_contents快一点,而且它更快,但更难实现,在你的Linux-Mashine上创建一个bash脚本,这个脚本只能被PHP调用。 – Oliver
http://codereview.stackexchange.com/help/on-topic – mickmackusa