0
点赞
收藏
分享

微信扫一扫

swoole性能实测 多协程与多进程


协程可以简单理解为线程,只不过这个线程是用户态的,不需要操作系统参与,创建销毁和切换的成本非常低,和线程不同的是协程没法利用多核 cpu 的,想利用多核 cpu 需要依赖 Swoole 的多进程模型。

上面是协程与进程区别,如果使用协程,没法利用多核CPU,我们现在来实测下 ,获取百度页面5000次
分别采用多协程与多线程模式来进行测试

测试环境:PHP 7.2.3 服务器配置: 1核1G swoole 4.0+

<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use function Swoole\Coroutine\run;
use Swoole\Process;
$s = microtime(true);
 for ($c = 5000; $c--;) {
     $process = new Process(function () use ($c) {
         if($c == 4999){
             echo microtime(true).'第一次';
         }
         if($c == 1){
             echo microtime(true).'第5000次';
         }
        file_get_contents("http://www.baidu.com");
     });
     $process->start();
 }
echo 'use ' . (microtime(true) - $s) . ' s';

下面使用协程环境下实现同样代码

<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use function Swoole\Coroutine\run;
use Swoole\Process;

// 此行代码后,文件操作,sleep,Mysqli,PDO,streams等都变成异步IO,见'一键协程化'章节
Runtime::enableCoroutine();
$s = microtime(true);

// Swoole\Coroutine\run()见'协程容器'章节
run(function() {
    // 10k pdo and mysqli read
    for ($c = 5000; $c--;) {
        Coroutine::create(function () use ($c){
            if($c == 4999){
                echo '第一次时间:'.microtime(true)."\r\n";
            }
            if($c == 0){
                echo '第5000次时间:'.microtime(true);
            }
            file_get_contents("http://www.baidu.com");
        });
    }

});
echo '程序总耗时:' . (microtime(true) - $s) . ' s'."\r\n";

这样可以看出来 如果使用协程去执行,创建速度会快很多,基本上QPS可以达到上万的级别
但是协程没办法用到多核。所以在进程使用情况下的话 多核CPU才有作用。


举报

相关推荐

0 条评论