pthreads 和 curl 之间的 PHP 测试

标签 php multithreading curl

我们计划构建实时竞价,我们正在评估 PHPJava 在吞吐量/响应时间等方面的性能比较。 (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);
?>

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

关于pthreads 和 curl 之间的 PHP 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19839746/

相关文章:

php CURL - 多个独立 session - 需要帮助!

PHP CURL 很少出现 SSL 连接错误

php - 无法在 Zend 中的分支文件夹之间执行 JOIN

php - 为什么我的卷没有复制到其Docker容器中?

java - `ArrayList::get` 是线程安全的吗?

asp.net - 如果我在asp.net中创建线程会怎样?

http - 使用 curl --fail 获取页面输出

php - 使用未定义常量 STDOUT - 假定为 'STDOUT'

PHP 比较两个 while 循环的结果

multithreading - 如何中断执行阻塞套接字连接的线程?