【问题标题】:Measure pagespeed "wait" in PHP在 PHP 中测量页面速度“等待”
【发布时间】:2017-10-11 15:31:45
【问题描述】:

我知道我可以通过以下方式测量外部网址的总网站加载时间:

$start_request = time();
file_get_contents($url);
$end_request = time ();
$time_taken = $end_request - $start_request;

但我不需要总网站加载,我只想测量服务器响应时间,就像它在结果的“等待”部分中显示的那样:

http://www.bytecheck.com/results?resource=https://www.example.com

我怎样才能用 php 做到这一点?

【问题讨论】:

  • 您可能想查看microtime() 而不是time()
  • 如果你想要像第一个字节的时间这样的细粒度统计,你需要使用像Curl这样的低级库。 curl_get_info 函数将满足您的需求。
  • @iainn 错字。这是curl_getinfo()
  • @CD001 microtime() 忍不住请完整阅读问题。

标签: php


【解决方案1】:

你不能像这样用 PHP 做到这一点。使用time()microtime(),您只能获得一个或多个命令所用的完整时间。

您需要一个可以访问网络层数据的工具。 cURL 可以为您执行此操作,但您必须 enable php curl,如果尚未完成。

PHP 可以获取结果并进行处理。

<?php
// Create a cURL handle
$ch = curl_init('http://www.example.com/');

// Execute
curl_exec($ch);

// Check if any error occurred
if (!curl_errno($ch)) {
  $info = curl_getinfo($ch);
  echo 'Took ', $info['total_time'], ' seconds to send a request to ', $info['url'], "\n";
}

// Close handle
curl_close($ch);

你在$info里有一堆信息喜欢

  • “文件时间”
  • “总时间”
  • “名称查找时间”
  • “连接时间”
  • “pretransfer_time”
  • “starttransfer_time”
  • “重定向时间”

完整列表可以在here找到

“等待”时间应该是starttransfer_time - pretransfer_time, 所以在你的情况下你需要:

$wait = $info['starttransfer_time'] - $info['pretransfer_time'];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多