.Net:如何模拟和测量完整的Web请求?

时间:2010-01-05 11:27:19

标签: .net webrequest

我正在尝试使用WebRequest测量请求,

但是我使用FireBug进行测量后会得到显着较小的结果。

我猜这是因为没有包含像图像和CSS这样的内容。

有没有办法衡量完整的网络请求?

我的代码:

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

    }

2 个答案:

答案 0 :(得分:1)

我不知道它是否适合您,但您可以使用WebBrowser控件,因为它会在触发DocumentCompleted事件之前请求页面的所有元素。

答案 1 :(得分:0)

您的代码只会测量代码完成所需的时间,代码不会等待所有字节到达客户端,这将花费比代码长得多的时间。

衡量的内容和位置取决于您希望进行优化的位置。如果您想在服务器轻负载时改善客户端的体验,那么Firebug(或Fiddler)将是一个测量的好地方。如果您在服务器负载不足时不想提高性能,那么代码分析器就是您需要的那种工具。

相关问题