我正在尝试用WebRequest衡量请求,

但是,我得到的效果要小于使用Firebug。

我猜这是因为不包括图像和CSS之类的内容。

有没有办法测量完整的Web请求?

我的代码:

        public string GetPageHtmlTime(string strUrl)
    {
        WebRequest request = null;
        WebResponse response = null;
        HttpWebResponse httpCurrentWeResponse = null;

        try
        {
            //making a request to the file.
            request = WebRequest.Create(strUrl);
            //set 5 seconds timeout for the request
            request.Timeout = 5 * 1000;

            //Stopwatch
            Stopwatch sw = new Stopwatch();
            sw.Start();

            //get the server response
            response = request.GetResponse();
            httpCurrentWeResponse = (HttpWebResponse)response;
            sw.Stop();

            //if the http response return any type of failure
            if (httpCurrentWeResponse.StatusCode != HttpStatusCode.OK || response == null)
                return "Error: " + httpCurrentWeResponse.StatusCode;

            response.Close();

            //Return time:
            return "OK time=" + sw.ElapsedMilliseconds.ToString("0,0");

        }
        catch (System.Exception ex)
        {
            return "Error: ex=" + ex.Message;
        }

    }
有帮助吗?

解决方案

我不知道这是否适合您,但是您可以使用 网页浏览器 控制,因为它将在启动之前请求页面的所有元素 DocumentCompleted 事件。

其他提示

您的代码只能衡量代码完成的时间,代码将不会等待所有字节到达客户端的所有字节,这将比代码大得多。

什么措施取决于您期望在哪里进行优化。如果您想在服务器处于轻载下时提高客户端的体验,那么Firebug(或Fiddler)将是一个很好的衡量场所。如果您在重载量下的服务器下没有提高服务器的性能,那么代码剖面人员将需要您所需的工具。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top