Created
September 21, 2019 19:10
-
-
Save hdvianna/120151b1fa6746491509fb1a753b2a97 to your computer and use it in GitHub Desktop.
Asynchronous Inserts with AMP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$init = microtime(true); | |
$filePath = $argv[1]; | |
$fileHandler = fopen($filePath, 'r'); | |
$lineNumber = 0; | |
while (($lineString = fgets($fileHandler)) !== false) { | |
$parameters = [$lineString, $lineNumber]; | |
$pdo = new PDO("mysql:dbname=hello_streams", "root"); | |
$statement = $pdo->prepare("INSERT INTO files_line(line_string, line_number) VALUES (?,?)"); | |
$statement->execute($parameters); | |
$lineNumber++; | |
} | |
fclose($fileHandler); | |
$elapsed = microtime(true) - $init; | |
var_dump($elapsed); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$init = microtime(true); | |
require './vendor/autoload.php'; | |
$filePath = $argv[1]; | |
Amp\Loop::run(function () use ($filePath) { | |
$config = Amp\Mysql\ConnectionConfig::fromString("host=127.0.0.1 user=root db=hello_streams"); | |
/** @var \Amp\Mysql\Pool $pool */ | |
$pool = Amp\Mysql\pool($config); | |
$fileHandler = fopen($filePath, 'r'); | |
$lineNumber = 0; | |
while (($lineString = fgets($fileHandler)) !== false) { | |
$parameters = [$lineString, $lineNumber]; | |
$pool->prepare("INSERT INTO files_line(line_string, line_number) VALUES (?,?)") | |
->onResolve(function ($error, $statement) use ($parameters) { | |
if (!$error) { | |
$statement->execute($parameters); | |
} | |
}); | |
$lineNumber++; | |
} | |
fclose($fileHandler); | |
}); | |
register_shutdown_function(function() use($init){ | |
$elapsed = microtime(true) - $init; | |
var_dump($elapsed); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Performance comparison between blocking and non-blocking inserts using AMP and traditional PDO
AMP (https://amphp.org/amp/) is a non-blocking concurrency framework for PHP.