码迷,mamicode.com
首页 > 其他好文 > 详细

Swoole 协程性能测试

时间:2020-07-11 17:23:32      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:utf8   创建   har   数据库   性能测试   异步io   php   文件读写   echo   

// 开启协程化,文件操作,sleep,Mysqli,PDO,streams等都变成异步IO
Co::set([‘hook_flags‘=> SWOOLE_HOOK_ALL]);

$s = microtime(true);

// 创建协程容器
Co\run(function() {
    // 开启100个协程执行usleep
    for ($c = 100; $c--;) {
        go(function () {
            for ($n = 100; $n--;) {
                usleep(1000);
            }
        });
    }

    // 开启100个协程执行100次文件读写
    for ($c = 100; $c--;) {
        go(function () use ($c) {
            $tmp_filename = "/tmp/test-{$c}.php";
            for ($n = 100; $n--;) {
                $self = file_get_contents(__FILE__);
                file_put_contents($tmp_filename, $self);
                assert(file_get_contents($tmp_filename) === $self);
            }
            unlink($tmp_filename);
        });
    }

    // 开启50个协程执行100次数据库查询
    for ($c = 50; $c--;) {
        go(function () {
            $pdo = new PDO(‘mysql:host=127.0.0.1;dbname=test;charset=utf8‘, ‘root‘, ‘root‘);
            $statement = $pdo->prepare(‘SELECT * FROM `user`‘);
            for ($n = 100; $n--;) {
                $statement->execute();
                assert(count($statement->fetchAll()) > 0);
            }
        });
    }
    
    // 开启50个协程执行100次数据库查询
    for ($c = 50; $c--;) {
        go(function () {
            $mysqli = new Mysqli(‘127.0.0.1‘, ‘root‘, ‘root‘, ‘test‘);
            $statement = $mysqli->prepare(‘SELECT `id` FROM `user`‘);
            for ($n = 100; $n--;) {
                $statement->bind_result($id);
                $statement->execute();
                $statement->fetch();
                assert($id > 0);
            }
        });
    }
});

echo ‘use ‘ . (microtime(true) - $s) . ‘ s‘;

Swoole 协程性能测试

标签:utf8   创建   har   数据库   性能测试   异步io   php   文件读写   echo   

原文地址:https://www.cnblogs.com/danhuang/p/13267762.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!