Skip to content

Instantly share code, notes, and snippets.

@Muqsit
Created May 9, 2020 09:35
Show Gist options
  • Save Muqsit/c79197a4239016d0786b3473fa163f8b to your computer and use it in GitHub Desktop.
Save Muqsit/c79197a4239016d0786b3473fa163f8b to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
$db = $argv[1];
$host = $argv[2];
$user = $argv[3];
$pwd = $argv[4];
$mysql = new mysqli($host, $user, $pwd, $db);
$mysql->query("CREATE TABLE IF NOT EXISTS stats(id INT UNSIGNED NOT NULL, stat_id ENUM('kills') NOT NULL, value INT NOT NULL, PRIMARY KEY(id, stat_id))");
$mysql->query("TRUNCATE TABLE stats");
$id = mt_rand();
$t = microtime(true);
testUPDATE($mysql, $id, "kills", 50);
$t = microtime(true) - $t;
echo "UPDATE: " . number_format($t * 1000, 10) . "ms" . PHP_EOL;
$id = mt_rand();
$t = microtime(true);
testINSERT($mysql, $id, "kills", 50);
$t = microtime(true) - $t;
echo "INSERT: " . number_format($t * 1000, 10) . "ms" . PHP_EOL;
$mysql->close();
function testINSERT(mysqli $mysql, int $id, string $stat_id, int $iterations) : void{
for($i = 0; $i < $iterations; ++$i){
$stmt = $mysql->prepare("INSERT INTO stats(id, stat_id, value) VALUES(?, ?, ?) ON DUPLICATE KEY UPDATE value=VALUES(value)");
$stmt->bind_param("isi", $id, $stat_id, $i);
$stmt->execute();
$stmt->close();
}
}
function testUPDATE(mysqli $mysql, int $id, string $stat_id, int $iterations) : void{
for($i = 0; $i < $iterations; ++$i){
$stmt = $mysql->prepare("UPDATE stats SET value=? WHERE id=? AND stat_id=?");
$stmt->bind_param("iis", $i, $id, $stat_id);
$stmt->execute();
$affected_rows = $stmt->affected_rows;
$stmt->close();
if($affected_rows === 0){
$stmt = $mysql->prepare("INSERT INTO stats(id, stat_id, value) VALUES(?, ?, ?)");
$stmt->bind_param("isi", $id, $stat_id, $i);
$stmt->execute();
$stmt->close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment