Created
December 10, 2023 13:37
-
-
Save crispy-computing-machine/6d154189eb3bccc38dec0448d89a8bcc to your computer and use it in GitHub Desktop.
Guzzle PHP Load Test
This file contains 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 | |
require 'vendor/autoload.php'; | |
use GuzzleHttp\Client; | |
use GuzzleHttp\Promise; | |
const TARGET_URL = 'https://example.com'; | |
const CONCURRENT_REQUESTS = 100; | |
$client = new Client(); | |
// Function to send a request and measure response time | |
function sendRequest($client) { | |
$start = microtime(true); | |
try { | |
$response = $client->get(TARGET_URL); | |
if ($response->getStatusCode() == 200) { | |
$duration = microtime(true) - $start; | |
return [ | |
'success' => true, | |
'duration' => $duration | |
]; | |
} | |
} catch (Exception $e) { | |
// Handle exception if needed | |
} | |
return ['success' => false]; | |
} | |
// Simulate concurrent requests | |
$promises = []; | |
for ($i = 0; $i < CONCURRENT_REQUESTS; $i++) { | |
$promises[] = $client->getAsync(TARGET_URL); | |
} | |
// Wait for all requests to complete | |
$responses = Promise\settle($promises)->wait(); | |
$successCount = 0; | |
$totalTime = 0; | |
foreach ($responses as $response) { | |
if ($response['state'] === 'fulfilled' && $response['value']->getStatusCode() === 200) { | |
$successCount++; | |
// Assuming the X-Response-Time header contains the response time in seconds. | |
// This is just an example, your server might not set this header. | |
$totalTime += floatval($response['value']->getHeaderLine('X-Response-Time')); | |
} | |
} | |
echo "Successful requests: {$successCount} out of " . CONCURRENT_REQUESTS . PHP_EOL; | |
echo "Average response time: " . ($successCount ? $totalTime / $successCount : 'N/A') . " seconds" . PHP_EOL; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment