.Net:如何模拟和测量完整的网络请求?
我正在尝试使用 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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道这是否适合您,但您可以使用 WebBrowser 控件,因为它将在触发
DocumentCompleted
事件之前请求页面的所有元素。I don't know if it's an option for you, but you can use the WebBrowser control, as it will request all the elements of the page before firing the
DocumentCompleted
event.您的代码只会测量代码完成所需的时间,代码不会等待所有字节到达客户端,这将比代码花费更长的时间。
采取何种措施以及在何处采取措施取决于您希望在何处进行优化。如果您想在服务器轻负载时改善客户端的体验,那么 Firebug(或 Fiddler)将是一个很好的测量位置。如果您不想在服务器负载较重时提高服务器的性能,那么代码分析器将是您需要的工具。
Your code will only measure how long it takes for the code complete, the code will not wait for all the bytes to arrive at the client which will take significantly longer than the code.
What and where measure depends on where you expect to make optimisations. If you want to improve the experience at the client when the server is under light load then Firebug (or Fiddler) would be a good place to be measuring. If you wan't to improve performance on the server when its under heavy load then code profilers would the sort of tool you would be needing.