Avatar ·

How to measure method execution time in C#? Stopwatch and other ways

Hi everyone! I'm a beginner C# developer and I've encountered a task: I need to accurately measure how long a specific method takes to execute in my application. For example, I'm writing a parser for a large file or performing complex mathematical calculations, and I want to understand which part of the code is slow.\n\nCurrently, I'm doing this:\n\n```csharp\nDateTime start = DateTime.Now;\n// my method\nThread.Sleep(1000); // simulating work\nDateTime end = DateTime.Now;\nTimeSpan duration = end - start;\nConsole.WriteLine($"Time: {duration.TotalMilliseconds} ms");\n```\n\nBut I noticed that the results sometimes fluctuate: sometimes 1000 ms, sometimes 1002 ms, sometimes 998 ms. I've also heard that DateTime.Now is not very accurate for such measurements.\n\nPlease advise how to properly measure method execution time? Are there any specific considerations I need to account for?