C# 如何测量网页的响应和加载时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/787622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:10:20  来源:igfitidea点击:

How can I measure the response and loading time of a webpage?

c#winformsmonitoring

提问by holiveira

I need to build a windows forms application to measure the time it takes to fully load a web page, what's the best approach to do that?

我需要构建一个 Windows 窗体应用程序来测量完全加载网页所需的时间,这样做的最佳方是什么?

The purpose of this small app is to monitor some pages in a website, in a predetermined interval, in order to be able to know beforehand if something is going wrong with the webserver or the database server.

这个小应用程序的目的是在预定的时间间隔内监视网站中的某些页面,以便能够提前知道网络服务器或数据库服务器是否出现问题。

Additional info:

附加信息:

I can't use a commercial app, I need to develop this in order to be able to save the results to a database and create a series of reports based on this info.

我不能使用商业应用程序,我需要开发它以便能够将结果保存到数据库并基于此信息创建一系列报告。

The webrequest solution seems to be the approach I'm goint to be using, however, it would be nice to be able to measure the time it takes to fully load the the page (images, css, javascript, etc). Any idea how that could be done?

webrequest 解决方案似乎是我将要使用的方,但是,能够测量完全加载页面(图像、css、javascript 等)所需的时间会很好。知道怎么做吗?

采纳答案by Craig T

If you just want to record how long it takes to get the basic page source, you can wrap a HttpWebRequest around a stopwatch. E.g.

如果只想记录获取基本页面源代码需要多长时间,可以将 HttpWebRequest 包裹在秒表周围。例如

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);

System.Diagnostics.Stopwatch timer = new Stopwatch();
timer.Start();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

timer.Stop();

TimeSpan timeTaken = timer.Elapsed;

However, this will not take into account time to download extra content, such as images.

但是,这不会考虑下载额外内容(例如图像)的时间。

[edit] As an alternative to this, you may be able to use the WebBrowser control and measure the time between performing a .Navigate() and the DocumentCompleted event from firing. I think this will also include the download and rendering time of extra content. However, I haven't used the WebBrowser control a huge amount and only don't know if you have to clear out a cache if you are repeatedly requesting the same page.

[编辑] 作为替代方案,您可以使用 WebBrowser 控件并测量执行 .Navigate() 和 DocumentCompleted 之间的时间。我认为这还将包括额外内容的下载和渲染时间。但是,我没有大量使用 WebBrowser 控件,只是不知道如果您重复请求同一页面,是否必须清除缓存。

回答by marcgg

You can use a software like these :

您可以使用以下软件:

http://www.cyscape.com/products/bhawk/page-load-time.aspx

http://www.cyscape.com/products/bhawk/page-load-time.aspx

http://www.trafficflowseo.com/2008/10/website-load-timer-great-to-monitor.html

http://www.trafficflowseo.com/2008/10/website-load-timer-great-to-monitor.html

Google will be helpful to find the one best suited for your needs.

Google 将有助于找到最适合您需求的产品。

回答by Daniel Moura

回答by John Rasch

Something like this would probably work fine:

像这样的事情可能会正常工作:

System.Diagnostics.Stopwatch sw = new Stopwatch()
System.Net.HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://www.example.com");
// other request details, credentials, proxy settings, etc...

sw.Start();
System.Net.HttpWebResponse res = (HttpWebResponse)req.GetResponse();
sw.Stop();

TimeSpan timeToLoad = sw.Elapsed;

回答by Neil Kodner

If you're using firefox install the firebug extension found at http://getfirebug.com. From there, choose the net tab, and it'll let you know the load/response time for everything on the page.

如果您使用 firefox,请安装在http://getfirebug.com 上找到的 firebug 扩展。从那里,选择 net 选项卡,它会让您知道页面上所有内容的加载/响应时间。

回答by razenha

Depending on how the frequency you need to do it, maybe you can try using Selenium (a automated testing tool for web applications), since it users internally a web browser, you will have a pretty close measure. I think it would not be too difficult to use the Selenium API from a .Net application (since you can even use Selenium in unit tests).

根据您需要执行的频率,也许您可​​以尝试使用 Selenium(一种用于 Web 应用程序的自动化测试工具),因为它在内部使用 Web 浏览器,您将有一个非常接近的度量。我认为从 .Net 应用程序使用 Selenium API 不会太难(因为您甚至可以在单元测试中使用 Selenium)。

Measuring this kind of thing is tricky because web browsers have some particularities when then download all the web pages elements (JS, CSS, images, iframes, etc) - this kind of particularities are explained in this excelent book (http://www.amazon.com/High-Performance-Web-Sites-Essential/dp/0596529309/).

衡量这种事情很棘手,因为 Web 浏览器在下载所有网页元素(JS、CSS、图像、iframe 等)时有一些特殊性——这种特殊性在这本优秀的书(http://www. amazon.com/High-Performance-Web-Sites-Essential/dp/0596529309/)。

A homemade solution probably would be too much complex to code or would fail to attend some of those particularities (measuring the time spent in downloading the html is not good enough).

自制的解决方案可能太复杂而无编码,或者无满足其中一些特殊性(衡量下载 html 所花费的时间还不够好)。

回答by JonnyBoats

One thing you need to take account of is the cache. Make sure you are measuring the time to download from the server and not from the cache. You will need to insure that you have turned off client side caching.

您需要考虑的一件事是缓存。确保您正在测量从服务器而不是从缓存下载的时间。您需要确保已关闭客户端缓存。

Also be mindful of server side caching. Suppose you download the pace at 9:00AM and it takes 15 seconds, then you download it at 9:05 and it takes 3 seconds, and finally at 10:00 it takes 15 seconds again.

还要注意服务器端缓存。假设您在上午 9:00 下载配速需要 15 秒,然后您在 9:05 下载它需要 3 秒,最后在 10:00 再次需要 15 秒。

What might be happening is that at 9 the server had to fully render the page since there was nothing in the cache. At 9:05 the page was in the cache, so it did not need to render it again. Finally by 10 the cache had been cleared so the page needed to be rendered by the server again.

可能发生的情况是,在 9 点服务器必须完全呈现页面,因为缓存中没有任何内容。在 9:05 页面在缓存中,因此不需要再次呈现它。最后到 10 时,缓存已被清除,因此该页面需要再次由服务器呈现。

I highly recommend that you checkout the YSlowaddin for FireFox which will give you a detailed analysis of the times taken to download each of the items on the page.

我强烈建议您查看 FireFox的YSlow插件,它会详细分析下载页面上每个项目所需的时间。

回答by bortzmeyer

I wrote once a experimentalprogramwhich downloads a HTML page andthe objects it references (images, iframes, etc).

我曾经写过一个实验程序,用于下载 HTML 页面及其引用的对象(图像、iframe 等)。

More complicated than it seems because there is HTTP negotiation so, some Web clients will get the SVG version of an image and some the PNG one, widely different in size. Same thing for <object>.

比看起来更复杂,因为有 HTTP 协商,所以一些 Web 客户端将获得图像的 SVG 版本和一些 PNG 版本,大小差异很大。同样的事情<object>

回答by merkuro

I'm often confronted with a quite similar problem. However I take a slight different approach: First of all, why should I care about static content at all? I mean of course it's important for the user, if it takes 2 minutes or 2 seconds for an image, but that's not my problem AFTER I fully developed the page. These things are problems while developing and after deployment it's not the static content, but it's the dynamic stuff that normally slows things down (like you said in your last paragraph). The next thing is, why do you trust that so many things stay constant? If someone on your network fires up a p2p program, the routing goes wrong or your ISP has some issues your server-stats will certainly go down. And what does your benchmark say for a user living across the globe or just using a different ISP? All I'm saying is, that you are benchmarking YOUR point of view, but that doesn't say much about the servers performance, does it?

我经常遇到一个非常相似的问题。但是我采取了稍微不同的方:首先,我为什么要关心静态内容?我的意思是当然这对用户很重要,如果图像需要 2 分钟或 2 秒,但这不是我完全开发页面后的问题。这些东西在开发和部署后都是问题,不是静态内容,而是通常会减慢速度的动态内容(就像你在上一段中说的那样)。接下来的事情是,你为什么相信这么多事情会保持不变?如果您网络上的某个人启动了 p2p 程序,则路由出错或您的 ISP 出现了一些问题,您的服务器统计数据肯定会下降。对于居住在全球各地或仅使用不同 ISP 的用户,您的基准测试有何意义?我只想说,

Why not let the site/server itself determine how long it took to load? Here is a small example written in PHP:

为什么不让站点/服务器自己决定加载需要多长时间?这是一个用 PHP 编写的小例子:

function microtime_float()
{
  list($usec, $sec) = explode(" ", microtime());
  return ((float)$usec + (float)$sec);
}

function benchmark($finish)
{
  if($finish == FALSE){  /* benchmark start*/    
    $GLOBALS["time_start"] = microtime_float();
  }else{ /* benchmark end */    
    $time = microtime_float() - $GLOBALS["time_start"]; 
    echo '<div id="performance"><p>'.$time.'</p></div>';
  }
}

It adds at the end of the page the time it took to build (hidden with css). Every couple of minutes I grep this with a regular expression and parse it. If this time goes up I know that there something wrong (including the static content!) and via a RSS-Feed I get informed and I can act.

它在页面末尾添加了构建所需的时间(用 css 隐藏)。每隔几分钟,我就会用正则表达式 grep 并解析它。如果这个时间增加,我知道有问题(包括静态内容!)并且通过 RSS-Feed 我得到通知,我可以采取行动。

With firebug we know the "normal" performance of a site loading all content (development phase). With the benchmark we get the current server situation (even on our cell phone). OK. What next? We have to make certain that all/most visitors are getting a good connection. I find this part really difficult and are open to suggestions. However I try to take the log files and ping a couple of IPs to see how long it takes to reach this network. Additionally before I decide for a specific ISP I try to read about the connectivity and user opinions...

使用 firebug,我们知道网站加载所有内容(开发阶段)的“正常”性能。通过基准测试,我们可以获得当前的服务器情况(甚至在我们的手机上)。好的。接下来是什么?我们必须确保所有/大多数访问者都获得了良好的联系。我觉得这部分真的很难,并且愿意接受建议。但是,我尝试获取日志文件并 ping 几个 IP 以查看到达该网络所需的时间。此外,在我决定使用特定的 ISP 之前,我会尝试阅读有关连接性和用户意见的信息...

回答by rinogo

tl;dr

tl;博士

Use a headless browser to measure the loading times. One example of doing so is Website Loading Time.

使用无头浏览器测量加载时间。这样做的一个例子是网站加载时间

Long version

长版

I ran into the same challenges you're running into, so I created a side-project to measure actual loading times. It uses Node and Nightmare to manipulate a headless ("invisible") web browser. Once all of the resources are loaded, it reports the number of milliseconds it took to fully load the page.

我遇到了您遇到的相同挑战,因此我创建了一个副项目来测量实际加载时间。它使用 Node 和 Nightmare 来操作无头(“隐形”)Web 浏览器。加载所有资源后,它会报告完全加载页面所需的毫秒数。

One nice feature that would be useful for you is that it loads the webpage repeatedly and can feed the results to a third-party service. I feed the values into NIXStats for reporting; you should be able to adapt the code to feed the values into your own database.

对您有用的一项很好的功能是,它可以重复加载网页并将结果提供给第三方服务。我将这些值输入 NIXStats 进行报告;您应该能够调整代码以将值输入到您自己的数据库中。

Here's a screenshot of the resulting values for our backend once fed into NIXStats: enter image description here

这是我们的后端输入 NIXStats 后的结果值的屏幕截图: 在此处输入图片说明

Example usage:

用示例:

website-loading-time rinogo$ node website-loading-time.js https://google.com
1657
967
1179
1005
1084
1076
...

Also, if the main bulk of your code must be in C#, you can still take advantage of this script/library. Since it is a command-line tool, you can call it from your C# code and process the result.

此外,如果您的大部分代码必须使用 C#,您仍然可以利用此脚本/库。由于它是一个命令行工具,因此您可以从 C# 代码中调用它并处理结果。

https://github.com/rinogo/website-loading-time

https://github.com/rinogo/website-loading-time

Disclosure: I am the author of this project.

披露:我是这个项目的作者。