If you want ease of use:
If you don't have strong accuracy requirements (true millisecond level accuracy - such as writing a high frames per second video game, or similar real-time simulation), then you can simply use the System.DateTime
structure:
// Could use DateTime.Now, but we don't care about time zones - just elapsed time
// Also, UtcNow has slightly better performance
var startTime = DateTime.UtcNow;
while(DateTime.UtcNow - startTime < TimeSpan.FromMinutes(10))
{
// Execute your loop here...
}
Change TimeSpan.FromMinutes
to be whatever period of time you require, seconds, minutes, etc.
In the case of calling something like a web service, displaying something to the user for a short amount of time, or checking files on disk, I'd use this exclusively.
If you want higher accuracy:
look to the Stopwatch
class, and check the Elapsed
member. It is slightly harder to use, because you have to start it, and it has some bugs which will cause it to sometimes go negative, but it is useful if you need true millisecond-level accuracy.
To use it:
var stopwatch = new Stopwatch();
stopwatch.Start();
while(stopwatch.Elapsed < TimeSpan.FromSeconds(5))
{
// Execute your loop here...
}
DateTime.Now
is slow (about 1000ns on my machine). You should useDateTime.UtcNow
instead because it's about 100 times faster due to not having to perform a timezone conversion. – Wretch