【问题标题】:How can I record duration of time in C#? [duplicate]如何在 C# 中记录持续时间? [复制]
【发布时间】:2016-03-31 11:42:38
【问题描述】:

我使用 C# 和 Xamarin 平台制作了一个随机数生成器程序。我把一个特定的数字作为目标,PC 必须随机取数字,当它找到目标数字时,它给了我尝试找到数字的次数。我只想念一件事,我想设置一个计时器,这样我就可以知道找到号码花了多少时间。当它找到它时,计时器停止记录。如何做到这一点?

【问题讨论】:

  • 看看StopWatch。这可以测量时间跨度。

标签: c# timer xamarin


【解决方案1】:
  1. 在函数开始前记录开始时间
  2. 在函数结束后记录完成时间
  3. 以秒或您想要的任何单位输出结果

        // 1) Log the start time before your function
        long startTime = DateTime.Now.Ticks;
    
        // 2) Log the finish time after your function
        double secondsElapsed = new TimeSpan(DateTime.Now.Ticks - startTime).TotalSeconds;
    
        // 3) Output result in seconds or whichever units you want
        Debug.WriteLine($"Function took: {secondsElapsed}");
    

【讨论】:

  • 欢迎来到 StackOverflow!我想评论你的回答。你没有错,但这不是最好的答案。使用 DateTime 结构不足以计算操作时间。
  • 那么更精确的是什么?
  • System.Diagnostics 命名空间中的Stopwatch 类是首选和推荐类。
【解决方案2】:

您可以使用 Stopwatch 类来记录持续时间:

// 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);

【讨论】:

  • 好的,我试试。当程序找到目标号码时,此计时器是否停止?对不起,我还是个初学者..
  • @Ayman Stopwatch 将在您拨打stopwatch.Stop() 时停止,所以当您找到目标号码时,只需拨打Stop() 即可获得预期结果。
  • @Dylan S,我希望它在找到号码时自动停止,因为可能需要几个小时才能找到它。
  • @Ayman 您在编写查找号码的代码吗?只需添加另一条停止秒表的行。找到号码后,您是否有某些原因无法停止秒表?代码遥不可及吗?
  • @Dylan S,我将其复制并放入我的程序中。但它没有用。程序找到了号码,但没有记录时间。
【解决方案3】:

您不需要为此设置计时器。只需执行此操作即可获取经过的毫秒数

var startTime = Environment.TickCount;
// do some work. 
var timeTaken =Environment.TickCount-startTime;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    相关资源
    最近更新 更多