Time difference between callings of a method

249 views Asked by At

One part of my program calls a certain method several times.

How can this method track the time between each time it is called?

I thought to use some global variables:

var lastTime = ?;
var currentTime = ?;
var elapsedTime = ?;

public DoSomething()
{
    currentTime = TimeRightNowInSeconds;
    elapsedTime = currentTime - lastTime;
    // do stuff with elapsedTime...
    lastTime = TimeRightNowInSeconds;
}

but I have no idea how I measure the time in seconds.

2

There are 2 answers

2
Stephan On

Consider using DateTime and TimeSpan (Be careful to use DateTime.UtcNow to avoid issues with daylight saving boundaries)

e.g.

var start = DateTime.UtcNow;
...
var end = DateTime.UtcNow;
var elapsed = end.Subtract(start); //elapsed is a TimeSpan
var elapsedSeconds = elsapsed.Seconds;

This can also be done with a Stopwatch (which is more accurate and doesn't suffer from problems with daylight saving boundaries)

var stopwatch = Stopwatch.StartNew();
...
stopwatch.Stop();
var elapsedSeconds = stopwatch.Elapsed.Seconds; //stopwatch.Elapsed is a TimeSpan
0
Timon Post On

In this solution you will see how to get the time between the method call Link

class Program
{
  static Stopwatch _stopWatch = new Stopwatch(); // stopwatch
  static long  _lastTime; // time in milliseconds


  static void Main(string[] args)
  {
     /* _lastTime will be 0 when first call ElapsedTime(). */
     ElapsedTime();

     /* Hold the current thread for 1000 milliseconds */ 
     Thread.Sleep(1000); 

     /* _lastTime will be 1000  when second call ElapsedTime(). */
     ElapsedTime(); 
     Thread.Sleep(2000);

     /* _lastTime will be 3000 when third call ElapsedTime(). */
     ElapsedTime();

     /* Thread.Sleep() is to simulate time between the calls of the method */ 
     /* _lastTime is in milliseconds*/
   }


   public static void ElapsedTime()
   {
     // check if stopwatch already started once
     if (_stopWatch .IsRunning) 
     {
         /* get the totlal elapsed milliseconds */
         _lastTime += _stopWatch .ElapsedMilliseconds;
         /* Restart stopwatch */
         _stopWatch .Restart();
      }
      else
      {
        _stopWatch .Start();
      }

     Console.WriteLine(_lastTime);
   }
}