0

我正在使用Amp进行一些测试,并尝试了解它如何通过异步运行 SQL 查询来帮助加速它们。我认为我做错了什么,因为这个测试文件的结果非常令人失望,而不是我所期望的。有什么我做错了吗?

下面的代码给了我这样的结果,第一个数字是 Amp\Mysql 并且由于某种原因它要慢很多:

0.37159991264343
0.10906314849854

PHP代码:

<?php
require 'vendor/autoload.php';
require 'Timer.php';

$runThisManyTimes = 1000;

///////////////////////////////////////////////////////////

use Amp\Mysql\ConnectionConfig;
use Amp\Loop;

Loop::run(function() use ($runThisManyTimes) {
    $timer = Timer::start();

    $config = ConnectionConfig::fromString(
        "host=127.0.0.1 user=test password=test db=test "
    );

    /** @var \Amp\Mysql\Pool $pool */
    $pool = Amp\Mysql\pool($config);

    /** @var \Amp\Mysql\Statement $statement */
    $statement = yield $pool->prepare("SELECT * FROM accounts WHERE id = :id");

    for ($i = 1; $i <= $runThisManyTimes; $i++) {
        /** @var \Amp\Mysql\ResultSet $result */
        $result = yield $statement->execute(['id' => '206e5903-98bd-4af5-8fb1-86a520e9a330']);

        while (yield $result->advance()) {
            $row = $result->getCurrent();

        }
    }

    $timer->stop();
    echo $timer->getSeconds();

    Loop::stop();
});

echo PHP_EOL;

///////////////////////////////////////////////////////////

$timer = Timer::start();

$pdo = new PDO('mysql:host=127.0.0.1;dbname=test', 'test', 'test');

$statement = $pdo->prepare("SELECT * FROM accounts WHERE id = :id");

for ($i = 1; $i <= $runThisManyTimes; $i++) {
    $statement->execute(['id' => '206e5903-98bd-4af5-8fb1-86a520e9a330']);
    $statement->fetch();
}

$timer->stop();
echo $timer->getSeconds();
4

2 回答 2

0

Parallel execution of MySQL is not productive when each thread takes less than, say, 1 second.

Each thread must use its own connection; establishing the connection takes some time.

Your particular benchmark (like most benchmarks) is not very useful. After the first execution of that single SELECT, all subsequent executions will probably take less than 1ms. It would be better to use a sequence of statements that reflect your app.

于 2021-03-05T23:04:36.267 回答
0

您的基准测试不包括任何并发性,因此它基本上就像 PDO 示例中的阻塞 I/O。amphp/mysql是 PHP 中的完整协议实现,因此预计它会比 PDO 的 C 实现慢。

如果您想了解非阻塞并发 I/O 是否对您的应用程序有好处,并且您当前正在使用顺序阻塞 PDO 查询,您应该使用非阻塞并发查询amphp/mysql而不是串行查询来对这些查询进行基准测试。

此外,amphp/mysql它可能没有像 PDO 背后的数据库驱动程序那样优化,但它允许 PDO 不支持的非阻塞并发查询。如果你做顺序查询,PDO暂时肯定会有更好的性能,但是amphp/mysql一旦涉及到并发就非常有用。

于 2021-07-08T19:56:47.993 回答