C#中精确计算运行时间的类

using System;
using System.Threading;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace TestEntity
{
    
///   <summary> 
    
///   进行精确操作计时的类。 
    
///   </summary> 
    public sealed class RunTime
    {
        
//   -----   私有对象 
        [DllImport("Kernel32.dll ")]
        
private static extern bool QueryPerformanceFrequency(out   long lpFrequency);

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

        
private long startTime, stopTime;
        
private long freq;

        
///   <summary> 
        
///   初始化   <see   cref= "RunTime "/>   类的新实例。 
        
///   </summary> 
        public RunTime()
        {
            
this.startTime = 0;
            
this.stopTime = 0;

            
if (QueryPerformanceFrequency(out   freq) == false)
                
throw new Win32Exception();
        }

        
///   <summary> 
        
///   开始执行计时。 
        
///   </summary> 
        public void Start()
        {
            Thread.Sleep(
0);
            QueryPerformanceCounter(
out   startTime);
        }

        
///   <summary> 
        
///   停止计时。 
        
///   </summary> 
        public void Stop()
        {
            QueryPerformanceCounter(
out   stopTime);
        }

        
///   <summary> 
        
///   获取计时后得到的计时时间。(单位为秒) 
        
///   </summary> 
        public double DurationSecs
        {
            
get
            {
                
//   判断是否执行了开始和结束 
                if (startTime == 0 || stopTime == 0)
                    
throw new InvalidOperationException("Unit_TimeVariableIsNull ");
                
return (double)(stopTime - startTime) / (double)freq;
            }
        }

        
///   <summary> 
        
///   获取计时后的计时时间。(单位为毫秒) 
        
///   </summary> 
        public float DurationMsel
        {
            
get
            {
                
if (startTime == 0 || stopTime == 0)
                    
throw new InvalidOperationException("Unit_TimeVariableIsNull");
                
return float.Parse((this.DurationSecs * 1000).ToString("##0.### "));
            }
        }
    }
}
posted @ 2011-04-08 17:43  MrNobody_123456  阅读(321)  评论(0编辑  收藏  举报