Skip to content

Instantly share code, notes, and snippets.

@naderman
Last active December 27, 2015 04:29
Show Gist options
  • Save naderman/7267028 to your computer and use it in GitHub Desktop.
Save naderman/7267028 to your computer and use it in GitHub Desktop.
There is a server which simply waits 2 seconds and then outputs Hello World. The client-parallel script triggers the curl request, then sleeps for a second (representing some amount of work) and then processes the response. The client-linear request triggers the curl request and immediately waits for the answer and processes it, then it continue…
<?php
$ch1 = curl_init();
// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://localhost/~naderman/sleep.php");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
//create the multiple cURL handle
$mh = curl_multi_init();
//add the two handles
curl_multi_add_handle($mh,$ch1);
$active = null;
//execute the handles
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($mh) != -1) {
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
// Simulated workload: sleep after the request is handled
sleep(1);
//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_close($mh);
<?php
$ch1 = curl_init();
// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://localhost/~naderman/sleep.php");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
//create the multiple cURL handle
$mh = curl_multi_init();
//add the two handles
curl_multi_add_handle($mh,$ch1);
$active = null;
//execute the handles
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
// Simulated workload: sleep while request is handled
sleep(1);
while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($mh) != -1) {
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_close($mh);
naderman@Montsoreau:~/tmp$ time php -f client-parallel.php
real 0m2.029s
user 0m0.012s
sys 0m0.012s
naderman@Montsoreau:~/tmp$ time php -f client-linear.php
real 0m3.029s
user 0m0.012s
sys 0m0.012s
<?php
sleep(2);
echo "Hello World!\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment