HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

Calculate the execution time of a method

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
calculatetimethemethodexecution

Problem

I have an I/O time-taking method which copies data from a location to another. What's the best and most real way of calculating the execution time? Thread? Timer? Stopwatch? Any other solution? I want the most exact one, and briefest as much as possible.

Solution

Stopwatch 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 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 contains a nice overview.

Code Snippets

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

Context

Stack Overflow Q#14019510, score: 1542

Revisions (0)

No revisions yet.