Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Best way to calculate time span

In my c# program, my requirement is to calculate a timespan for business logic execution that is inside a foreach loop I have to store time span.

I am using following code

for (int i = 0; i < 100; i++)
{
    DateTime start= DateTime.Now; 
    // Business logic
    DateTime end= DateTime.Now; 
    TimeSpan time = start.Subtract(end);
    // Save timespan in log file
}

Please correct me whether I am using right code, or do I need to modify for better performance and result.

like image 280
Hemant Kothiyal Avatar asked Dec 29 '11 06:12

Hemant Kothiyal


3 Answers

You should use a Stopwatch. The Stopwatch is much more accurate for time measurement than the wall time clock.

var sw = Stopwatch.StartNew();
// business logic
sw.Stop();
TimeSpan time = sw.Elapsed;
like image 87
Albin Sunnanbo Avatar answered Nov 17 '22 23:11

Albin Sunnanbo


The easiest way would be to:

TimeSpan time = DateTime.Now - start;

Alternatively, you could use a stopwatch which gives more accurate results. See http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx for how to work with a stopwatch.

like image 34
Pieter van Ginkel Avatar answered Nov 17 '22 23:11

Pieter van Ginkel


It looks like you're using the timespan to measure performance. Your code is fine, however you should be aware that DateTimes are only so precise (about 10-15ms on most machines -- see the "Useless Timer Mechanism" section here for an explanation).

DateTimes are also not contiguous; what if the first DateTime is retrieved just before daylight savings time kicks in, and the latter one just after? An operation that takes one second could show up as taking an hour, or even negative time. Even with all times in UTC, there's potential problems when the user changes the time manually, or jumps caused by the computer going to sleep and waking up, etc.

A better alternative would be to use the Stopwatch class, which is designed for this sort of thing and uses a high-precision timer internally (via the QueryPerformanceCounter() Win32 function).

like image 1
Cameron Avatar answered Nov 18 '22 00:11

Cameron