Introduction: In Android 4.0 development, sending Http requests is no longer allowed to be executed in the main process and must be executed in a thread. The reason is that the response time of the Http interface may block the event monitoring of the main process (the same is true for .Net development). However, since PHP does not have the concept of multi-threading, how to efficiently execute multiple http requests in PHP? The answer is to use curl_multi_init, so I did an experiment.
The following is the http interface that simulates the request. The code is very simple. The sleep time is controlled by the parameter time passed in by get.
$s_time=intval($_GET['time']); sleep($s_time); echo 'hello';
$start=microtime(true); for($i=1;$i<=5;++$i) { $ch=curl_init("http://test.binbin.com/curl/test.php?time={$i}"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_exec($ch); } $end=microtime(true); echo $end-$start;
$start=microtime(true); $ch_list=array(); $multi_ch=curl_multi_init(); for($i=1;$i<=5;++$i) { $ch_list[$i]=curl_init("http://test.binbin.com/curl/test.php?time={$i}"); curl_setopt($ch_list[$i], CURLOPT_RETURNTRANSFER, true); curl_multi_add_handle($multi_ch, $ch_list[$i]); } $running=false; do { usleep(10000); curl_multi_exec($multi_ch, $running); }while ($running>0); $end=microtime(true); echo $end-$start;
Postscript: I saw many people reporting on blogs the problem of excessive CPU usage using curl_multi_init. In fact, it can be solved by adding usleep. Because if the data is not returned, curl_multi_exec will continue to execute, consuming CPU resources.
The above introduces php curl to send http requests in batches, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.