Home
Map
BenchmarkUse Stopwatch to benchmark a method, computing the average number of nanoseconds.
C#
This page was last reviewed on Jan 15, 2024.
Benchmark. How fast does a C# method run, and is it faster than a different implementation? If we have a solid knowledge of how fast code executes, we can develop more efficient programs.
Stopwatch
With benchmarking, we can make smarter decisions. Most of the programs we use every day have been benchmarked many times. However, incorrect benchmarks have a negative value.
Example. In the current benchmark program, we use if-directives as this eliminates the problem where the order of tests running affects performance.
Note Change "_max" depending on the code of each iteration. Start smaller and push the limit up.
for
Note 2 Adjust _max higher or lower based on how slow your iterations are. This could be automated, but is not that important.
Convert Nanoseconds
Console.WriteLine
Version 1 Each benchmark should have a description, so that the end result is not too confusing to read.
Version 2 This version of the code should be slightly different (but hopefully have the same approximate effect).
#define VERSION1 using System; using System.Diagnostics; // Other class. class Program { public static void Main() { const int _max = 10000000; var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { #if VERSION1 // Code. #endif #if VERSION2 // Code. #endif } s1.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } }
??? ns Version 1 description ??? ns Version 2 description
If directives. It is probably better to only run one test per program execution. In previous benchmarking programs, it is common to find that the second loop runs faster than the first.
And This problem is completely solved if we just run one version at a time.
Directive
An example optimization. The Dictionary collection in the base class library is a huge optimization. But developers sometimes write code that results in twice as many lookups.
Dictionary TryGetValue
More complex benchmark. For an example of a more complex benchmark, check the Tuple page. It performs several tests on Tuples to determine how fast tuples are.
Tuple
Summary. Benchmarking encourages careful thinking about your code. It saves nanoseconds from your software. It also improves the depth of your understanding.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 15, 2024 (new example).
Home
Changes
© 2007-2024 Sam Allen.