10

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.

Josh
  • 8,082
  • 5
  • 43
  • 41
Qusyaire Ezwan
  • 279
  • 4
  • 8
  • 18

4 Answers4

30

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);
avs099
  • 10,937
  • 6
  • 60
  • 110
4
 (endRunningProg  - startRunningProg).TotalMilliseconds ;

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

Community
  • 1
  • 1
Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
1

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

Luis Hernandez
  • 453
  • 5
  • 8
0

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

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
Brad Cunningham
  • 6,402
  • 1
  • 32
  • 39