// program.cs

// PerfTimer 及 测试程序

 TestPerformance
{
    internal sealed class PerfTimer
    {
        [DllImport(
"Kernel32.dll")]
        
private static extern bool QueryPerformanceCounter(
            
out long lpPerformanceCount);

        [DllImport(
"Kernel32.dll")]
        
private static extern bool QueryPerformanceFrequency(
            
out long lpFrequency);

        
private long startTime, stopTime;
        
private long freq;

        
// Constructor
        public PerfTimer()
        {
            startTime 
= 0;
            stopTime 
= 0;

            
if (QueryPerformanceFrequency(out freq) == false)
            {
                
// high-performance counter not supported
                throw new Win32Exception();
            }
        }

        
// Start the timer
        public void Start()
        {
            
// lets do the waiting threads there work
            Thread.Sleep(0);
            QueryPerformanceCounter(
out startTime);
        }

        
// Stop the timer
        public void Stop()
        {
            QueryPerformanceCounter(
out stopTime);
        }

        
// Returns the duration of the timer (in seconds)
        public double Duration
        {
            
get
            {
                
return (double)(stopTime - startTime) / (double)freq;
            }
        }
    }
 

    
class Program
    {
        
static void Main(string[] args)
        {
            Console.WriteLine(
"Press any key to continueWindows API高精度计时 C#版");
            Console.ReadKey();

            PerfTimer pt 
= new PerfTimer();     // create a new PerfTimer object
            pt.Start();                             // start the timer

            
for(int i=0; i<10000; i++)
            {
                
string s = string.Format("This is test round {0}", i);//"This is test round "+i.ToString();
                Console.WriteLine(s);
            }

            pt.Stop();
            Console.WriteLine(
"Duration: {0} second(s)"n", pt.Duration); // print the duration of the timed code

            Console.WriteLine(
"Press any key to continueWindows API高精度计时 C#版");
            Console.ReadKey();
        }
    }

}

 参考文献:

【1】http://www.codeproject.com/KB/cs/highperformancetimercshar.aspx


 

相关文章:

  • 2022-01-23
  • 2021-12-12
  • 2022-01-14
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-02
猜你喜欢
  • 2022-12-23
  • 2021-12-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案