相关疑难解决方法(0)

是DateTime.Now是测量函数性能的最佳方法吗?

我需要找到一个瓶颈,并且需要准确地测量时间.

以下代码段是衡量性能的最佳方法吗?

DateTime startTime = DateTime.Now;

// Some execution process

DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);
Run Code Online (Sandbox Code Playgroud)

.net c# performance datetime timer

466
推荐指数
14
解决办法
6万
查看次数

简单的无锁秒表

根据 MSDN,类Stopwatch实例方法对于多线程访问并不安全。这也可以通过检查个别方法来确认。

然而,由于我只需要在代码中的几个地方使用简单的“经过时间”计时器,我想知道它是否仍然可以无锁地完成,使用类似的东西:

public class ElapsedTimer : IElapsedTimer
{
    /// Shared (static) stopwatch instance.
    static readonly Stopwatch _stopwatch = Stopwatch.StartNew();

    /// Stopwatch offset captured at last call to Reset
    long _lastResetTime;

    /// Each instance is immediately reset when created
    public ElapsedTimer()
    { 
        Reset();
    }

    /// Resets this instance.
    public void Reset()
    {
        Interlocked.Exchange(ref _lastResetTime, _stopwatch.ElapsedMilliseconds);
    }

    /// Seconds elapsed since last reset.
    public double SecondsElapsed
    {
        get
        {
             var resetTime = Interlocked.Read(ref _lastResetTime);
             return (_stopwatch.ElapsedMilliseconds - resetTime) / …
Run Code Online (Sandbox Code Playgroud)

c# atomic stopwatch lockless

5
推荐指数
1
解决办法
723
查看次数

秒表经过时间线程安全

好吧,我有一个相当简单的问题,但我找不到简洁的答案。我想知道在读取仍在运行的lock()一段时间的已用属性时是否需要担心调用语句。Stopwatch

这也是Stopwatch我应该用来测量线程运行时间的东西。我读过其他类似的问题,DispatchTimer可以使用 a 。我也研究过使用事件,但是对于如此简单的事情来说,这似乎是很大的开销,如果这是完全错误的并且我应该使用事件,请告诉我。一些简单的代码来说明我在说什么。

 class foo
 {
      private bool _isRunning { get; set; }
      private Stopwatch sw { get; set; }
      public void StartThread()
      {
          this._isRunning = true;
          new Thread(new ThreadStart(this.DoWork)).Start();
          this.sw.Restart();
      }     
      public void StopThread()
      {
          this._isRunning = false;
          this.sw.Stop();
      }
      private void DoWork()
      {
          while(this._isRunning)
          {
               //Do Stuff
          }
      }
      public TimeSpan GetRuntime()
      {
          return this.sw.Elapsed;
      }
      public foo()
      {
          _isRunning = false;
          sw = new Stopwatch();
      }
 }
Run Code Online (Sandbox Code Playgroud)

假设在使用上述类的应用程序中,我要在GetRuntime() …

.net c# multithreading thread-safety

4
推荐指数
1
解决办法
4166
查看次数