C# 用HTTP在C语言中测量TTFB和TTLB#

C# 用HTTP在C语言中测量TTFB和TTLB#,c#,C#,我正在寻找在向特定网页发出http web请求时测量TTFB(到第一个字节的时间)和TTLB(到最后一个字节的时间)的方法 我如何用C#进行测量 我正在编写一个监视工具来测量访问网页的TTFB和TTLB 您可以使用执行阻塞调用,并测量所需时间: using (var wc = new WebClient()) { var sw = new Stopwatch(); sw.Start(); wc.DownloadData("

我正在寻找在向特定网页发出http web请求时测量TTFB(到第一个字节的时间)和TTLB(到最后一个字节的时间)的方法

我如何用C#进行测量


我正在编写一个监视工具来测量访问网页的TTFB和TTLB

您可以使用执行阻塞调用,并测量所需时间:

     using (var wc = new WebClient())
     {
         var sw = new Stopwatch();
         sw.Start();
         wc.DownloadData("http://www.stackoverflow.com");
         sw.Stop();
        Console.WriteLine("Elapsed time (ms): " + sw.ElapsedMilliseconds.ToString());
     }
     Console.ReadLine();
或者,如果需要异步执行,请执行以下操作:

    static Stopwatch sw;
    static void Main(string[] args)
    {
        using (var wc = new WebClient()) {
            sw = new Stopwatch();
            sw.Start();
            wc.DownloadDataCompleted +=wc_DownloadDataCompleted;
            wc.DownloadDataAsync(new Uri("http://www.stackoverflow.com"));

        }
        Console.ReadLine();
    }

    static void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
    {
        sw.Stop();
        Console.WriteLine("Elapsed time (ms): " + sw.ElapsedMilliseconds);
    }

当然,您可能希望捕获错误并检查http响应,以确保请求成功,但您知道这一点。

您可以使用执行阻塞调用并测量所需的时间:

     using (var wc = new WebClient())
     {
         var sw = new Stopwatch();
         sw.Start();
         wc.DownloadData("http://www.stackoverflow.com");
         sw.Stop();
        Console.WriteLine("Elapsed time (ms): " + sw.ElapsedMilliseconds.ToString());
     }
     Console.ReadLine();
或者,如果需要异步执行,请执行以下操作:

    static Stopwatch sw;
    static void Main(string[] args)
    {
        using (var wc = new WebClient()) {
            sw = new Stopwatch();
            sw.Start();
            wc.DownloadDataCompleted +=wc_DownloadDataCompleted;
            wc.DownloadDataAsync(new Uri("http://www.stackoverflow.com"));

        }
        Console.ReadLine();
    }

    static void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
    {
        sw.Stop();
        Console.WriteLine("Elapsed time (ms): " + sw.ElapsedMilliseconds);
    }

当然,您可能希望捕获错误并检查http响应,以确保请求成功,但您明白了。到目前为止回答的代码将为您提供TTLB,要获得TTFB,尽管不是100%准确,但您必须收听
WebClient
类的事件
DownloadProgressChanged
,在第一次呼叫时,记录秒表迄今为止记录的时间,而不停止它。

到目前为止应答的代码将为您提供TTLB,要获得TTFB,尽管不是100%准确,但您必须收听
WebClient
类的事件
DownloadProgressChanged
,在第一次呼叫时,记录秒表迄今为止记录的时间,而不停止它。

你为什么要做日期数学而不是使用秒表类?你为什么要做日期数学而不是秒表课?