How long does my code take to run?

后端 未结 6 1533
轮回少年
轮回少年 2021-02-05 22:43

How can I find out how much time my C# code takes to run?

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-05 23:02

    As others have said, the Stopwatch class is good for the simple timing side of things. Other bits to bear in mind though:

    • Your code may generate objects which will need to be garbage collected after you've stopped the stopwatch
    • Conversely your timing may include other objects being garbage collected even if they have nothing to do with your code
    • If you start timing before you run your method for the first time, it will include JIT time
    • If you take a very short time, that leads to very unpredictable results - for benchmarking I tend to prefer running code for many seconds, to account for the app being interrupted by other processes etc.

    If you're interested in benchmarking, I have the MiniBench project which I must get round to working on again at some point - it's not quite where I want it to end up, but it's a start. I talk more about what I want to achieve with it in this blog post.

提交回复
热议问题