百万数据写入 PHP-FPM与Swoole性能对比

php7.2 for循环写入

<?php
//连接数据库
$dbhost = '127.0.0.1';  // mysql服务器主机地址
$dbuser = 'root';            // mysql用户名
$dbpass = '123456';          // mysql用户名密码
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(!$conn )
{
    die('连接错误: ' . mysqli_error($conn));
}
$start = microtime(true);
for($i = 10; $i<1000000; $i++){
    $title = "title";
    $author = "pcity.top";
    $content = "content";
    $date = date("h:i:s");
    mysqli_select_db($conn, 'dev' );  //需要先行创建数据库 表
    $sql = "INSERT INTO excel_test (title, author, content, create_time) VALUES ('$title','$author','$content','$date')";
    $result = mysqli_query($conn, $sql);
    if(!$result) {
        echo $i;
    }
}
$end = microtime(true);
$time = $end - $start;
echo "插入一百万数据执行时间为:".$time;  //4881.6208279133

mysqli_close($conn);
echo "ok";
?>

swoole4.5.5 协程写入

<?php
declare(strict_types=1);

use Swoole\Coroutine;
use Swoole\Database\PDOConfig;
use Swoole\Database\PDOPool;
use Swoole\Runtime;

// 线程数
const N = 100;

Runtime::enableCoroutine();
// 记录时间
$start = microtime(true);
// 开启容器
Coroutine\run(function () {
//mysql 连接池 因为是教程 就没有去检测在连接中特殊情况
    $pool = new PDOPool((new PDOConfig)
        ->withHost('127.0.0.1')
        ->withPort(3306)
        ->withDbName('dev')
        ->withCharset('utf8mb4')
        ->withUsername('root')
        ->withPassword('123456')
    );
//循环写入数据库
    for ($n = 100; $n--;) {
        Coroutine::create(function () use ($pool) {
			$title = "title";
			$author = "pcity.top";
			$content = "content";
			$date = date("h:i:s");
            $pdo = $pool->get();
            for ($i = 10000; $i--;) {
                $statement = $pdo->prepare('INSERT INTO excel_test (`title`,`author`, `content`, `create_time`) VALUES (?,?,?,?,)');
                if (!$statement) {
                    throw new RuntimeException('Prepare failed');
                }
                $result = $statement->execute([$title,$author,$content,$date]);
                if (!$result) {
                    throw new RuntimeException('Execute failed');
                }
            }
            $pool->put($pdo);
        });
    }
});

$time = microtime(true) - $start;
echo "插入一百万数据".N."个协程执行时间为:".$time. PHP_EOL;// 338.07238388062

总结

FPM: 4881.6208279133 s

swoole: 338.07238388062

Swoole协程的速度是FPM下速度10倍以上,并且协程数更多影响,Swoole 可能会更强劲

彼特城博客
请先登录后发表评论
  • latest comments
  • 总共0条评论