Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate duration using Date.Time.Now in C#

Tags:

c#

time

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.

like image 267
Qusyaire Ezwan Avatar asked Jun 13 '12 02:06

Qusyaire Ezwan


People also ask

How do I convert DateTime to TimeSpan?

To convert a DateTime to a TimeSpan you should choose a base date/time - e.g. midnight of January 1st, 2000, and subtract it from your DateTime value (and add it when you want to convert back to DateTime ). If you simply want to convert a DateTime to a number you can use the Ticks property. Save this answer.

How do you find the difference between two time?

Calculate the duration between two times First, identify the starting and an ending time. The goal is to subtract the starting time from the ending time under the correct conditions. If the times are not already in 24-hour time, convert them to 24-hour time. AM hours are the same in both 12-hour and 24-hour time.

What is the difference between DateTime and TimeSpan?

The TimeSpan struct represents a duration of time, whereas DateTime represents a single point in time. Instances of TimeSpan can be expressed in seconds, minutes, hours, or days, and can be either negative or positive.

How do you subtract DateTime?

Subtract(DateTime) This method is used to subtract the specified date and time from this instance. Syntax: public TimeSpan Subtract (DateTime value); Return Value: This method returns a time interval that is equal to the date and time represented by this instance minus the date and time represented by value.


1 Answers

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);
like image 172
avs099 Avatar answered Oct 30 '22 01:10

avs099