Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient method to measure time?

I'm in a situation in which I need to do an action X ammount of times per second (refresh a PictureBox or pull bytes from socket buffer). I was wondering if there is a proper way to do this. I did some research and I found few ways of going about this.

  1. I can work in a while loop and constantly ask OS what time is it to check if X ammount of time had passed.(DateTime.UtcNow)

  2. I can work in a while loop and put it to sleep for a period of time.

  3. I can work in a while loop and use Clock class to check for elapsed time.

  4. Use Timer Class to raise event.

These are all ways I know to make something happen periodically. Second method is not very precise but I put it here for completion sake. Are there other methods I should be aware of? Which one has the least overhead?

I'm working in VisualStudio 2015 C# and version of .NET 4.6.1

like image 542
Jahith Avatar asked Oct 15 '25 21:10

Jahith


1 Answers

Use Stopwatch, which is using high precision timer compared to DateTime.Now

DateTime.Now is good for about milliseconds precision while Stopwatch for microseconds.

// Create new stopwatch.
Stopwatch stopwatch = new Stopwatch();

// Begin timing.
stopwatch.Start();

// Do something.
for (int i = 0; i < 1000; i++)
{
    Thread.Sleep(1);
}

// Stop timing.
stopwatch.Stop();

// Write result.
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
like image 134
becike Avatar answered Oct 18 '25 09:10

becike