我想向同一个域上的不同页面发送大约50个请求,然后使用DOM对象获取文章的urls。
问题是,这个请求数需要超过30秒。
for ($i = 1; $i < 51; $i++)
{
    $url = 'http://example.com/page/'.$i.'/';             
    $client = new Zend_Http_Client($url);
    $response = $client->request();
    $dom = new Zend_Dom_Query($response); // without this two lines, execution is also too long
    $results = $dom->query('li');         //
}有没有什么方法可以加快速度呢?
发布于 2013-07-04 17:40:45
这是一个设计上的通用问题--而不是代码本身。如果你正在做一个超过50个项目的for循环,每个项目打开一个对远程uri的请求,事情会变得非常慢,因为每个请求都会等待,直到远程uri响应。例如:一个请求需要大约0.6秒才能完成,乘以50,你得到的执行时间是30秒!
另一个问题是,大多数per服务器将其每个客户端的(开放)连接限制为特定数量。因此,即使你能够同时处理50个请求(你目前还不能),事情也不会有明显的加速。
在我的选择中,只有一个解决方案(没有任何深层次的更改):更改每次执行的请求量。例如,每个(脚本)-call只有5- 10个块,并通过外部调用触发它们(例如,通过cron运行它们)。
Todo:构建一个包装器函数,该函数能够将当前运行的状态(“我在上次运行时请求了1- 10,所以现在我必须调用11 - 20)保存到一个文件或数据库中,并由cron触发此函数。
示例代码(未测试),以获得更好的声明;
[...]
private static $_chunks = 10; //amout of calls per run
public function cronAction() {
    $lastrun = //here get last run parameter saved from local file or database
    $this->crawl($lastrun);
}
private function crawl($lastrun) {
    $limit = $this->_chunks + $lastrun;
    for ($i = $lastrun; $i < limit; $i++)
    {
        [...] //do stuff here
    }
    //here set $lastrun parameter to new value inside local file / database
}
[...]发布于 2013-07-03 20:37:44
我想不出一个方法来加速它,但是你可以在PHP中增加超时限制,如果这是你关心的:
for($i=1; $i<51; $i++) {
  set_time_limit(30);    //This restarts the timer to 30 seconds starting now
  //Do long things here
}https://stackoverflow.com/questions/17444930
复制相似问题