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.
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.
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 of the code at a time.
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 24, 2024 (simplify).