pthreads 和 curl 之间的 PHP 测试


PHP testing between pthreads and curl

我们计划建立实时竞价,我们正在评估PHP在吞吐量/响应时间等方面与Java相比的效果。(Java部分由团队的其他成员负责)

初始开始:

我有一个测试脚本,它可以与不同的服务器建立 50 http 连接。

第一种方法- 我正在使用curl_multi_init功能,并在 7 秒内得到响应。

第二种方法- 我正在使用PHP pthreads api并尝试进行并行调用并期望相同的响应时间或更短。但平均总时间约为 25 秒

这是代码

   <?php
    $g_request_arr = array(
        '0' => array(
            'request_url' => 'https://www.google.co.uk/?#q=56%2B12'
        ),
        ..
        ..
        ..
        '49'=>array(
            'request_url' => 'https://www.google.co.uk/?#q=256%2B132'
        )
    );

    class ChildThread extends Thread {
        public function __construct($urls) {
            $this->data = $urls;
        }
        public function run(){
            foreach($this->data as  $url_info ){
                $url = $url_info['request_url'];
                file_get_contents($url);
            }  
            $this->synchronized(function($thread){
                $thread->notify();
            }, $this);
        }
    }
    $thread = new ChildThread($g_request_arr);
    $thread->start();
    $thread->synchronized(function($thread){    
    }, $thread);

?>

我想知道上面的代码中缺少什么,或者是否可以在 7 秒内做出响应。

您正在请求一个线程中的所有数据,这是一个更好的方法:

<?php
class WebRequest extends Stackable {
    public $request_url;
    public $response_body;
    public function __construct($request_url) {
        $this->request_url = $request_url;
    }
    public function run(){
        $this->response_body = file_get_contents(
            $this->request_url);
    }
}
class WebWorker extends Worker {
    public function run(){}
}
$list = array(
    new WebRequest("http://google.com"),
    new WebRequest("http://www.php.net")
);
$max = 8;
$threads = array();
$start = microtime(true);
/* start some workers */
while (@$thread++<$max) {
    $threads[$thread] = new WebWorker();
    $threads[$thread]->start();
}
/* stack the jobs onto workers */
foreach ($list as $job) {
    $threads[array_rand($threads)]->stack(
        $job);
}
/* wait for completion */
foreach ($threads as $thread) {
    $thread->shutdown();
}
$time = microtime(true) - $start;
/* tell you all about it */
printf("Fetched %d responses in %.3f seconds'n", count($list), $time);
$length = 0;
foreach ($list as $listed) {
    $length += strlen($listed["response_body"]);
}
printf("Total of %d bytes'n", $length);
?>

这使用多个工作线程,您可以通过更改$max进行调整。如果您有 1000 个请求要处理,那么创建 1000 个线程就没有多大意义。