Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure elapsed time using DateTime class?

Tags:

c#

time

I am encountering a strange behavior here. Control never comes out of the do-while loop. On debugging i found that the value of the variable interval decreases during some of the loops, instead of increasing! I'm missing something obvious here, but can't figure it out.

static void Main(string[] args)
{
    int interval = 0;
    DateTime startTime = DateTime.Now;

    //Task1(); //Task1 can take 4-8 seconds to complete

    do
    {
        Thread.Sleep(100);
        interval = (DateTime.Now - startTime).Milliseconds;
    } while (interval < 10000); //wait for at-least ten seconds from program start, before executing task2

    //Task2();
}
like image 479
Martin Avatar asked Aug 30 '17 12:08

Martin


People also ask

How do you find the elapsed time in Java?

currentTimeMillis(); long elapsedTime = end - start; In the example above, we're using the “System. currentTimeMillis()” static method. The method returns a long value, which refers to the number of milliseconds since January 1st, 1970, in UTC.

What are used to measure the elapsed time of events?

How do you calculate elapsed time? Calculating elapsed time can be done by measuring the time between the start and finish of an event. This can be done by the use of simple addition or subtraction.


1 Answers

Don't use DateTime for measuring time intervals.

Use Stopwatch class, which was designed exactly for this purpose

var clock = new Stopwatch();
clock.Start();
do
{
    // do something
}
while (clock.ElapsedMilliseconds < 10000)
clock.Stop();

Note: Of course you can use DateTime for measuring time, but if you need precision less then second then Stopwatch is right tool for the job.
And Stopwatch have much more readable and easy to use methods for measuring time

In your particular case: "wait for at-least ten seconds from program start, before executing task2" you can use asynchronous approach

var task1 = StartTask1();

await Task.Delay(10000); // next line will be executed approximately after 10 s

var task2 = StartTask2();
like image 173
Fabio Avatar answered Oct 16 '22 06:10

Fabio