pthreads和curl之间的PHP测试

cas*_* 48 2 php multithreading 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);


?>
Run Code Online (Sandbox Code Playgroud)

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

Joe*_*ins 6

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

<?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);
?>
Run Code Online (Sandbox Code Playgroud)

这使用多个工作人员,您可以通过更改$ max来调整.如果你有1000个处理请求,创建1000个线程没什么意义.