Qusyaire Ezwan
Qusyaire Ezwan

Reputation: 279

Calculate duration using Date.Time.Now in C#

I need to calculate duration for my system running. My system in c#. I've set:

DateTime startRunningProg = Date.Time.Now("o");

after a few process.

I set :

DateTime endRunningProg = Date.Time.Now("o");

How to calculate duration for my system running in millisec or sec.

Upvotes: 10

Views: 27438

Answers (4)

Luis Hernandez
Luis Hernandez

Reputation: 628

Using Stopwatch :

Stopwatch timer = Stopwatch.StartNew();
Thread.Sleep(1234);
timer.Stop();
TimeSpan timeSpan = timer.Elapsed;
Console.WriteLine("Total processing time... {0:00}:{1:00}:{2:00}.{3}", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds);
// OUTPUT   Total processing time... 00:00:01.243

Using DateTime:

DateTime start = DateTime.Now;
Thread.Sleep(1234);
DateTime end = DateTime.Now;
TimeSpan diff = (end  - start);
Console.WriteLine("Total processing time... {0:00}:{1:00}:{2:00}.{3}", diff.Hours, diff.Minutes, diff.Seconds, diff.Milliseconds);
// OUTPUT   Total processing time... 00:00:01.234

Online example: https://dotnetfiddle.net/Aqvc5G

Upvotes: 1

Brad Cunningham
Brad Cunningham

Reputation: 6501

Like has been mentioned, if you are trying to do precise timings then you should be using the StopWatch class.

If you actually want to do Date math and figure out the difference between two dates I suggest you check out Noda Time

Upvotes: 0

Preet Sangha
Preet Sangha

Reputation: 65496

 (endRunningProg  - startRunningProg).TotalMilliseconds ;

But @avs is right - use Stopwatch class. See this question Stopwatch vs. using System.DateTime.Now for timing events

Upvotes: 4

avs099
avs099

Reputation: 11227

to accurately measure elapsed time, use StopWatch class:

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;

// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
    ts.Hours, ts.Minutes, ts.Seconds,
    ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);

Upvotes: 30

Related Questions