Dusan
Dusan

Reputation: 5144

Absolute Time Measurement

When I start some process, I take DateTime.Now and remember it as StartTime.

Later in process, I substract StartTime from DateTime.Now to calculate the time passed between these two - between start and current time.

Now, the problem is that this approach is not always accurate - during process, time might be changed by windows using time servers or even manually by user.

Are there some other approaches to measure time as described that will always work properly - even if the windows time is changed in meanwhile?

Upvotes: 2

Views: 1888

Answers (3)

Pranay Rana
Pranay Rana

Reputation: 176956

you can make use of this : Get time of Code Execution Using StopWatch

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//instead of this there is line of code that you are going to execute
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine(elapsedTime);
Console.ReadLine();

Upvotes: 1

YoryeNathan
YoryeNathan

Reputation: 14532

Use a Stopwatch.

var a = Stopwatch.StartNew(); // Initializes and starts running
var b = new Stopwatch(); // Initializes and doesn't start running

var c = a.Elapsed; // TimeSpan

a.Stop();
a.Start();
a.Reset();

The Stopwatch is like a watch itself, so it doesn't count on the computer's clock. Just start one at the beginning, and check Elapsed to see how much time has passed.

Upvotes: 1

MiMo
MiMo

Reputation: 11983

There is the StopWatch class - http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx

Upvotes: 2

Related Questions