C#:这是标杆级的准确吗​​? [英] C#: Is this benchmarking class accurate?

查看:118
本文介绍了C#:这是标杆级的准确吗​​?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的类,以基准我的一些方法。但它是准确的?我有点新标杆,定时,等等,所以以为我可以问一些反馈在这里。另外,如果是好的,也许别人可以使用它,以及:)

I created a simple class to benchmark some methods of mine. But is it accurate? I am kind of new to benchmarking, timing, et cetera, so thought I could ask for some feedback here. Also, if it is good, maybe somebody else can make use of it as well :)

public static class Benchmark
{
    public static IEnumerable<long> This(Action subject)
    {
        var watch = new Stopwatch();
        while (true)
        {
            watch.Reset();
            watch.Start();
            subject();
            watch.Stop();
            yield return watch.ElapsedTicks;
        }
    }
}

您可以使用它像这样

var avg = Benchmark.This(() => SomeMethod()).Take(500).Average();



任何反馈?它看起来是相当稳定的,准确的,或者有我错过了什么?

Any feedback? Does it look to be pretty stable and accurate, or have I missed something?

推荐答案

这大约是准确的,因为你可以得到一个简单的基准。但也有一些因素不是你的控制之下:

It is about as accurate as you can get for a simple benchmark. But there are some factors not under your control:


  • 从其他过程的系统负载

  • 前堆的国家/基准时

您可以做一些关于最后一点,基准是罕见的情况,其中一个 GC.Collect的 可以得到辩护。你可以称之为主题一次事先以消除任何JIT的问题。但是,这需要对主题通话是独立的。

You could do something about that last point, a benchmark is one of the rare situations where calling GC.Collect can be defended. And you might call subject once beforehand to eliminate any JIT issues. But that requires calls to subject to be independent.

public static IEnumerable<TimeSpan> This(Action subject)
{
    subject();     // warm up
    GC.Collect();  // compact Heap
    GC.WaitForPendingFinalizers(); // and wait for the finalizer queue to empty

    var watch = new Stopwatch();
    while (true)
    {
        watch.Reset();
        watch.Start();
        subject();
        watch.Stop();
        yield return watch.Elapsed;  // TimeSpan
    }
}

有关的奖金,你的类应检查 System.Diagnostics.Stopwatch.IsHighResolution 现场。如果是关闭的,你只有一个很粗的(20毫秒)的分辨率。

For bonus, your class should check the System.Diagnostics.Stopwatch.IsHighResolution field. If it is off, you only have a very coarse (20 ms) resolution.

但是,一个普通的PC机,并在后台运行许多服务上,它是永远不会是非常准确的。

But on an ordinary PC, with many services running in the background, it is never going to be very accurate.

这篇关于C#:这是标杆级的准确吗​​?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆