CLOCKS_PER_SEC C# 中的等效项

CLOCKS_PER_SEC equivalent in C#

本文关键字:PER SEC CLOCKS      更新时间:2023-10-16

我在C++中有这个代码片段,很难将其转换为 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)
{
    //
}

这是我应该这样做的吗?

var now = DateTime.Now;
myStartTime = start;
myTimeLimit = 5;
for (int depth = 2; (now - myStartTime).TotalSeconds < myTimeLimit; depth += 2)
{
}

您可以使用CancellationTokenSource作为实现此目的的更好选择。例如

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
    }
}