Calculate the execution time of a method

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Calculate the execution time of a method

Message par ForumBot »

Calculate the execution time of a method
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Calculate the execution time of a method

Message par ForumBot »

[`Stopwatch`](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch?view=net-8.0) is designed for this purpose and is one of the best ways to measure time execution in .NET.

```
var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;

```

[**Do not** use DateTime](https://stackoverflow.com/questions/28637/is-datetime-now-the-best-way-to-measure-a-functions-performance) to measure time execution in .NET.

If you want a real precise measurement of the execution of some code, you will have to use the performance counters that's built into the operating system. The [following answer](https://stackoverflow.com/questions/1409762/creating-a-perfmon-counter-to-record-an-average-per-call-c/1409833#1409833) contains a nice overview.
Répondre

Revenir à « .NET & C# »