测试redis响应时间
·
function test_redis_connection_speed($host = '127.0.0.1', $port = 6379, $password = '', $db = 0, $iterations = 100)
{
$connection_times = array();
for ($i = 1; $i <= $iterations; $i++) {
$start_time = microtime(true);
try {
// Create a new Redis connection
$redis = new Redis();
$redis->connect($host, $port);
$redis->auth($password);
// Optionally select a database
$redis->select($db);
// Send a PING command to check if the connection is alive
$ping_result = $redis->ping();
if ($ping_result) {
$end_time = microtime(true);
$connection_times[] = $end_time - $start_time;
echo "Iteration $i: Connection established successfully. Time taken: " . number_format($end_time - $start_time, 6) . " seconds\n";
} else {
echo "Iteration $i: Unexpected response from PING command.\n";
}
} catch (Exception $e) {
echo "Failed to establish connection on iteration $i: " . $e->getMessage() . "\n";
break;
}
// Close the connection after each iteration
$redis->close();
}
if (!empty($connection_times)) {
$avg_time = array_sum($connection_times) / count($connection_times);
$min_time = min($connection_times);
$max_time = max($connection_times);
sort($connection_times); // Sort for median calculation
$median_time = ($connection_times[floor((count($connection_times) - 1) / 2)] + $connection_times[ceil((count($connection_times) - 1) / 2)]) / 2;
echo "\nTest completed after $iterations iterations.\n";
echo "Average connection time: " . number_format($avg_time, 6) . " seconds\n";
echo "Median connection time: " . number_format($median_time, 6) . " seconds\n";
echo "Minimum connection time: " . number_format($min_time, 6) . " seconds\n";
echo "Maximum connection time: " . number_format($max_time, 6) . " seconds\n";
}
}
// Call the function with desired parameters
test_redis_connection_speed('127.0.0.1', 6379, 'password', 0, 20);
更多推荐

所有评论(0)