Skip to content

Instantly share code, notes, and snippets.

@colorfield
Last active July 18, 2020 20:11
Show Gist options
  • Save colorfield/fbda4f0a8286a61624ecebc9f01470ce to your computer and use it in GitHub Desktop.
Save colorfield/fbda4f0a8286a61624ecebc9f01470ce to your computer and use it in GitHub Desktop.
Testing performances of curl / curl_multi with php
<?php
/**
* @file Testing multiple curl / single curl.
*/
/**
* Multi curl.
*
* @param array $urls
*/
function testMultiCurl(array $urls) {
$urlCount = count($urls);
$curlHandles = [];
$curlMultipleHandle = curl_multi_init();
for ($i = 0; $i < $urlCount; $i++) {
$url = $urls[$i];
$curlHandles[$i] = curl_init($url);
curl_setopt($curlHandles[$i], CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curlHandles[$i], CURLOPT_HEADER, TRUE);
curl_setopt($curlHandles[$i], CURLOPT_NOBODY, TRUE);
curl_multi_add_handle($curlMultipleHandle, $curlHandles[$i]);
}
do {
$status = curl_multi_exec($curlMultipleHandle, $running);
if ($running) {
curl_multi_select($curlMultipleHandle);
}
} while ($running && $status === CURLM_OK);
for ($i = 0; $i < $urlCount; $i++) {
$results[] = curl_getinfo($curlHandles[$i], CURLINFO_HTTP_CODE);
curl_multi_remove_handle($curlMultipleHandle, $curlHandles[$i]);
}
curl_multi_close($curlMultipleHandle);
print("Multi curl\n");
print_r($results);
}
/**
* Single curl.
*
* @param array $urls
*/
function testSingleCurl(array $urls) {
$results = [];
foreach ($urls as $url) {
$curlHandle = curl_init($url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curlHandle, CURLOPT_HEADER, TRUE);
curl_setopt($curlHandle, CURLOPT_NOBODY, TRUE);
curl_exec($curlHandle);
$results[] = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
curl_close($curlHandle);
}
print("Single curl\n");
print_r($results);
}
$urls = [
"https://duckduckgo.com",
"https://www.drupal.org",
"https://laravel.com",
"https://mastodon.social",
"https://www.nova.fr",
"https://www.arte.tv",
"https://www.raspberrypi.org",
];
//testSingleCurl($urls);
testMultiCurl($urls);
//======================================
// Output for `time php multi-curl.php`
//======================================
//
// Single curl (3 runs)
//-------------------------------------
// php multi-curl.php 0.14s user 0.03s system 12% cpu 1.325 total
// php multi-curl.php 0.14s user 0.03s system 4% cpu 3.533 total
// php multi-curl.php 0.14s user 0.03s system 2% cpu 6.283 total
//
// Multi curl (3 runs)
//-------------------------------------
// php multi-curl.php 0.12s user 0.02s system 35% cpu 0.400 total
// php multi-curl.php 0.11s user 0.03s system 34% cpu 0.392 total
// php multi-curl.php 0.11s user 0.02s system 37% cpu 0.360 total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment