【问题标题】:Time difference between callings of a method方法调用之间的时间差
【发布时间】:2016-12-21 07:32:24
【问题描述】:

我的程序的一部分多次调用某个方法。

此方法如何跟踪每次调用之间的时间?

我想使用一些全局变量:

var lastTime = ?;
var currentTime = ?;
var elapsedTime = ?;

public DoSomething()
{
    currentTime = TimeRightNowInSeconds;
    elapsedTime = currentTime - lastTime;
    // do stuff with elapsedTime...
    lastTime = TimeRightNowInSeconds;
}

但我不知道如何以秒为单位测量时间。

【问题讨论】:

标签: c# time mono timing


【解决方案1】:

考虑使用DateTime 和TimeSpan(小心使用 DateTime.UtcNow 以避免出现夏令时边界问题)

例如

var start = DateTime.UtcNow;
...
var end = DateTime.UtcNow;
var elapsed = end.Subtract(start); //elapsed is a TimeSpan
var elapsedSeconds = elsapsed.Seconds;

这也可以通过Stopwatch 来完成(更准确,并且不会遇到夏令时边界问题)

var stopwatch = Stopwatch.StartNew();
...
stopwatch.Stop();
var elapsedSeconds = stopwatch.Elapsed.Seconds; //stopwatch.Elapsed is a TimeSpan

【讨论】:

  • elapsedSeconds 是什么类型?如果不是 int,我如何使它成为 int?
  • 是的,它是一个整数。
【解决方案2】:

在这个解决方案中,您将看到如何获取方法调用之间的时间 Link

class Program
{
  static Stopwatch _stopWatch = new Stopwatch(); // stopwatch
  static long  _lastTime; // time in milliseconds


  static void Main(string[] args)
  {
     /* _lastTime will be 0 when first call ElapsedTime(). */
     ElapsedTime();

     /* Hold the current thread for 1000 milliseconds */ 
     Thread.Sleep(1000); 

     /* _lastTime will be 1000  when second call ElapsedTime(). */
     ElapsedTime(); 
     Thread.Sleep(2000);

     /* _lastTime will be 3000 when third call ElapsedTime(). */
     ElapsedTime();

     /* Thread.Sleep() is to simulate time between the calls of the method */ 
     /* _lastTime is in milliseconds*/
   }


   public static void ElapsedTime()
   {
     // check if stopwatch already started once
     if (_stopWatch .IsRunning) 
     {
         /* get the totlal elapsed milliseconds */
         _lastTime += _stopWatch .ElapsedMilliseconds;
         /* Restart stopwatch */
         _stopWatch .Restart();
      }
      else
      {
        _stopWatch .Start();
      }

     Console.WriteLine(_lastTime);
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多