Reputation: 1653
I've this code snippet in C++ and have a hard time converting it to C#
clock_t now = clock();
myStartTime = start;
myTimeLimit = 5 // in seconds
for (int depth = 2; ((double)(now - myStartTime)) / (double)CLOCKS_PER_SEC < myTimeLimit; depth += 2)
{
//
}
Is this how I should do it?
var now = DateTime.Now;
myStartTime = start;
myTimeLimit = 5;
for (int depth = 2; (now - myStartTime).TotalSeconds < myTimeLimit; depth += 2)
{
}
Upvotes: 0
Views: 386
Reputation: 12641
You can make use of CancellationTokenSource
as a better alternative to achieve this. For example
var clt = new CancellationTokenSource(5000);
Task.Run(() => DoSomething(clt.Token));
private static void DoSomething(CancellationToken cltToken)
{
for (int depth = 2; !cltToken.IsCancellationRequested; depth += 2)
{
// . . .
}
if (cltToken.IsCancellationRequested) {
// Time limit reached before finding best move at this depth
}
}
Upvotes: 2