0

There are many questions around there asking what is the best way to measure elapsed time for benchmarking and/or testing, but I'm looking for something a bit different.

I would like to measure the elapsed time in a loop, and break it when it reaches a given amount of time. To be clear, see the example below:

int elapsedTime = 0;
while (elapsedTime < MAX_TIME) {
    doSomething();
    elapsedTime += time-taken-by-doSomething;
}

The doSomething method won't always take the same time (can go from ~3ms to ~50ms) so I really need to measure it each time it gets called.

What would be the best way to get elapsed time in this conditions (ie. not a benchmark, not a test)?

Casto
  • 305
  • 4
  • 10

1 Answers1

0

Try using the Stopwatch class

Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
while (stopwatch.Elapsed < MAX_TIME) {
    //Do something
}

Be careful if you are doing multithreaded stuff though

Community
  • 1
  • 1
bhh
  • 176
  • 1
  • 5