同时运行多个帖子请求并行,改进和优化脚本的速度.多线程可能



我希望您可以帮助我优化并加快我编写的脚本以检索多个来源的数据。现在,根据一天中的时间,脚本往往需要2到10分钟的时间。

全部和任何帮助将得到非常批准。

解释脚本:
我使用foreach循环通过五个不同的URL运行,然后每个URL将执行五个帖子请求,并将结果数据写入文件。

我希望的是:
为了提高脚本的速度,我希望可以将五个URL中的每个URL中的每个函数都放在单独的功能中,然后运行彼此平行的五个函数。

我读过的选择之一是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);
};

您可以使用curl_multi http://php.net/manual/manual/en/function.curl-multi-init.php,或者您可以使用诸如https://github之类的已书面库。com/jmathai/php-multi-curl,但这些库是用curl_multi编写的。

最新更新