How to get a Fast .Net Http Request

后端 未结 3 1629
不知归路
不知归路 2021-02-03 11:26

I need an Http request that I can use in .Net which takes under 100 ms. I\'m able to achieve this in my browser so I really don\'t see why this is such a problem in code.

3条回答
  •  暖寄归人
    2021-02-03 11:36

    When benchmarking, it is best to discard at least the first two timings as they are likely to skew the results:

    • Timing 1: Dominated by JIT overhead i.e. the process of turning byte code into native code.
    • Timing 2: A possible optimization pass for the JIT'd code.

    Timings after this will reflect repeat performance much better.

    The following is an example of a test harness that will automatically disregard JIT and optimization passes, and run a test a set number of iterations before taking an average to assert performance. As you can see the JIT pass takes a substantial amount of time.

    JIT:410.79ms

    Optimize:0.98ms.

    Average over 10 iterations:0.38ms

    Code:

    [Test]
    public void WebRequest_Should_Get_Html_Quickly()
    {
        private const int TestIterations = 10;
        private const int MaxMilliseconds = 100;
    
        Action test = () =>
        {
           WebRequest.Create("http://localhost/iisstart.htm").GetResponse();
        };
    
        AssertTimedTest(TestIterations, MaxMilliseconds, test);
    }
    
    private static void AssertTimedTest(int iterations, int maxMs, Action test)
    {
        double jit = Execute(test); //disregard jit pass
        Console.WriteLine("JIT:{0:F2}ms.", jit);
    
        double optimize = Execute(test); //disregard optimize pass
        Console.WriteLine("Optimize:{0:F2}ms.", optimize);
    
        double totalElapsed = 0;
        for (int i = 0; i < iterations; i++) totalElapsed += Execute(test);
    
        double averageMs = (totalElapsed / iterations);
        Console.WriteLine("Average:{0:F2}ms.", averageMs);
        Assert.Less(averageMs, maxMs, "Average elapsed test time.");
    }
    
    private static double Execute(Action action)
    {
        Stopwatch stopwatch = Stopwatch.StartNew();
        action();
        return stopwatch.Elapsed.TotalMilliseconds;
    }
    

提交回复
热议问题