测量连接时间就像这个PHP的好习惯吗?还有更好的方法吗?

时间:2017-11-24 09:31:39

标签: php loops curl

我需要连续多次测量一次web服务的响应时间,我以前就这样做了一次连接(没有循环),但现在这样做是不对的,尽管它似乎工作。任何建议都将不胜感激。

$servername = "x.x.x.x";
$username = "xxx";
$password = "xxx";
$db = "xxx";

for($i=0; $i<10;++$i){

  $ch = $_SESSION['cURL'];
  $time_pre = microtime(true);
  $data = curl_exec($ch);
  $time_pro = microtime(true);
  $exec_time[$i] = $time_pro - $time_pre;
 }

$conn = mysqli_connect($servername, $username, $password, $db);

//Check connection
if ($conn->connect_error){
    die("Connection failed: " . $conn->connect_error);
}

date_default_timezone_set('Europe/Madrid');
$date = date('Y-m-d H:i:s');
var_dump($date);

for($i=0; $i<10;++$i){
    $query = "INSERT INTO DB(time, date) VALUES('$exec_time[$i]', '$date')";
    $result2=mysqli_query($conn, $query);
}

1 个答案:

答案 0 :(得分:2)

我最终在评论中使用了Lawrence Cherone的建议。它比我使用的更快更干净。 http://php.net/manual/en/function.curl-multi-exec.php

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$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);
    }
}

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);