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 ?
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 ?
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:
A few years ago, C# blogger Eric Lippert wrote a multi-part series on exactly that topic:
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 |
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.