A project to demonstrate the correct way to measure execution time in .NET. 🛠️ Learn how to avoid common pitfalls, optimize performance, and measure time like a pro!
This repository contains examples of three methods to measure execution time in .NET:
DateTime.UtcNow: A commonly used but inefficient approach.Stopwatch.StartNew: Better, but introduces unnecessary overhead.Stopwatch.GetTimestamp: The most accurate and efficient method.
Each method is benchmarked using BenchmarkDotNet to provide proof of performance. 💡
- .NET 8.0
- C#
- BenchmarkDotNet
TimeMeasurementInDotNet/
├── TimeMeasurementInDotNet/ # Main project folder
│ ├── Program.cs # Entry point for running benchmarks
│ ├── TimeMeasurementBenchmarks.cs # Contains benchmark tests for all three methods
├── .gitignore # Ignore unnecessary files in Git
├── LICENSE # License information
├── README.md # Project documentation
Follow these steps to run the benchmarks and view the results:
-
Clone the Repository
git clone https://github.com/<your-username>/TimeMeasurementInDotNet.git cd TimeMeasurementInDotNet
-
Restore Dependencies
dotnet restore
-
Run Benchmarks
Make sure you are in Release mode before running:dotnet run --configuration Release
-
View Results
Results will appear in the console and as.htmland.mdfiles under:bin/Release/net8.0/BenchmarkDotNet.Artifacts/results/
| 🛠️ Method | 🕒 Mean | 📉 Error | 📊 StdDev | 💾 Allocated |
|---|---|---|---|---|
| MeasureWithDateTime | 509.0 ms | 1.77 ms | 1.66 ms | 1.1 KB |
| MeasureWithStopwatchStartNew | 509.6 ms | 1.34 ms | 1.25 ms | 1.14 KB |
| MeasureWithStopwatchGetTimestamp | 509.3 ms | 1.42 ms | 1.32 ms | 1.1 KB |
🔍 Insights:
DateTime.UtcNow: Adds unnecessary overhead due to internal date calculations.Stopwatch.StartNew: Allocates memory unnecessarily.Stopwatch.GetTimestamp: Fast, precise, and memory-efficient.
This project is licensed under the MIT License. See the LICENSE file for details.
- Medium Article: Read the Full Explanation