7

How can I do test for performance in C#?

All that I know now is to use:

Stopwatch sw = new Stopwatch();

sw.Start();
{
     //code to test
}
sw.Stop();

Is there any other way to do this or is the above method wrong ?

TheBoyan
  • 6,802
  • 3
  • 45
  • 61
NIlesh Lanke
  • 1,213
  • 9
  • 26
  • 35
  • As long as you calculate averages and don't require it to be super-accurate, it seems perfectly okay for me. – fjdumont Dec 13 '11 at 08:56
  • @ Maheep , i m nt using any tool. – NIlesh Lanke Dec 13 '11 at 08:59
  • @NIleshLanke I concur with whoever voted this as a duplicate of this question (http://stackoverflow.com/questions/3927/what-are-some-good-net-profilers). The stopwatch is just going to tell you how much time something took, this is not performance. Profilers allow you to do all kind of things like memory consumption etc in addition to how long things took to run. – gideon Dec 13 '11 at 12:53
  • 1
    Have you tryed BenchmarkDotNet? it can test alot more then the time it takes a code to run, GC, Memory and such -> https://github.com/dotnet/BenchmarkDotNet Edit: Just notice the date on the topic ... sry – Camadas May 27 '22 at 14:19

3 Answers3

5

Stopwatch is a good, simple way to measure the execution time of specific blocks of code. For large-scale performance testing good tools are available, such as the ones listed in the following SO question:


If you benchmark your code yourself (using Stopwatch or some other low-level tool), there are some things to watch out for:

  • Run the test in an environment that most accurately resembles the target environment: Release build, no debugger attached, similar hardware.
  • Keep in mind that the first run of a piece of code can have significantly different performance characteristics then subsequent runs (due to caching, JIT-ing, one-time initializers, etc.). If you are interested in the average execution time, do at least one "warmup" iteration first.

A few years ago, C# blogger Eric Lippert wrote a multi-part series on exactly that topic:

Heinzi
  • 167,459
  • 57
  • 363
  • 519
2

A better option to test the performance metrics in dotnet is BenchMarkDotnet.

Example:

 public class Md5VsSha256
 {       

    [Benchmark]
    public byte[] Sha256() => sha256.ComputeHash(data);

    [Benchmark]
    public byte[] Md5() => md5.ComputeHash(data);
 }

Benchmark results

Method Mean Error StdDev
Sha256 100.90 us 0.5070 us 0.4494 us
Md5 37.66 us 0.1290 us 0.1207 us
Matt Qafouri
  • 1,449
  • 2
  • 12
  • 26
0

Basically you can benefit from everything in System.Diagnostics namespace. Like PerformanceCounter class etc. Stopwatch being one of the alternatives you can use to measure time of execution.

If you have some money to spend you could use RedGate Develper Bundle for .NET It has Performance profiler, Memory profiler etc.

There also other cheaper alternatives.

Community
  • 1
  • 1
TheBoyan
  • 6,802
  • 3
  • 45
  • 61