andrew4582

HiPerfTimer

Jul 18th, 2011
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.11 KB | None | 0 0
  1. using System.ComponentModel;
  2. using System.Runtime.InteropServices;
  3. using System.Threading;
  4.  
  5. namespace Core
  6. {
  7.     public class HiPerfTimer
  8.     {
  9.         [DllImport("Kernel32.dll")]
  10.         private static extern bool QueryPerformanceCounter(
  11.             out long lpPerformanceCount);
  12.  
  13.         [DllImport("Kernel32.dll")]
  14.         private static extern bool QueryPerformanceFrequency(
  15.             out long lpFrequency);
  16.  
  17.         private long _startTime, _stopTime;
  18.         private long _freq;
  19.  
  20.         // Constructor
  21.         public HiPerfTimer()
  22.         {
  23.             _startTime = 0;
  24.             _stopTime = 0;
  25.  
  26.             if (QueryPerformanceFrequency(out _freq) == false)
  27.             {
  28.                 // high-performance counter not supported
  29.                 throw new Win32Exception();
  30.             }
  31.         }
  32.  
  33.         // Start the timer
  34.         public void Start()
  35.         {
  36.             // lets do the waiting threads there work
  37.             Thread.Sleep(0);
  38.  
  39.             QueryPerformanceCounter(out _startTime);
  40.         }
  41.  
  42.         // Stop the timer
  43.         public void Stop()
  44.         {
  45.             QueryPerformanceCounter(out _stopTime);
  46.         }
  47.  
  48.         // Returns the duration of the timer (in seconds)
  49.         public double Duration
  50.         {
  51.             get
  52.             {
  53.                 double d = (_stopTime - _startTime);
  54.                 return d / _freq;
  55.             }
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment