您的位置:首页 > 编程语言 > C#

C#中获取精确时间

2011-12-10 21:21 309 查看
程序中获取精确的时间,有时是非常必要的。常用的是,在测试程序的性能时,需要使用到精确的时间计时。或者其他情况要用到精确的时间。这就要用到一个函数QueryPerformanceCounter()。用法是从第一次调用QueryPerformanceCounter(),过一段时间后再次调用该函数结束的.两者之差除以QueryPerformanceFrequency()的频率就是开始到结束之间的秒数。由于计时函数本身是要耗费很少的时间,所以但一般忽略不计。
有一点要注意的是,如果在多处理器的电脑上使用这个函数需要,需要指定调用的处理器。因为在不同的处理器上会得到不同的结果。
下面的类可以实现该功能。
public class QueryPerformance  {          [DllImport("Kernel32.dll")]          private static extern bool QueryPerformanceCounter(out long performanceCount);            [DllImport("Kernel32.dll")]          private static extern bool QueryPerformanceFrequency(out long frequency);            private long begintTime = 0;//开始时间                    private long endTime = 0;//结束时间            private long frequency= 0;//处理器频率                    public long BegintTime          {            get{return begintTime;}          }                     public long EndTime          {            get{return endTime;}          }                     public long Frequency          {            get{return frequency;}          }              public QueryPerformance()          {              QueryPerformanceFrequency(frequency)//获取频率          }            public void Start()          {              QueryPerformanceCounter(begintTime);          }            public void Stop(bool showRecord)          {              QueryPerformanceCounter(endTime);                if (showRecord)              {                  Console.WriteLing(string.Format("用时:{0}s", TastTime));              }          }            public double TastTime//花费时间:单位S          {              get              {                 if(frequency>0)                  return (double)(endTime - begintTime) / frequency;                 else                  return 0;              }          }  }
调用:
QueryPerformance queryPerformance = new QueryPerformance();            QueryPerformance.Start();                    //代码块、函数等                     QueryPerformance.Stop(true);
本文出自 “西北白杨树” 博客,请务必保留此出处http://yangyoushan.blog.51cto.com/7229571/1276601
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: