专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »DotNet » 获取当前时间:一个获取高精度时间类 »正文

获取当前时间:一个获取高精度时间类

来源: 发布时间:星期四, 2009年2月12日 浏览:122次 评论:0


如果你觉得用DotNet自带DateTime获取时间精度不够解决思路方法是通过QueryPerformanceFrequency和QueryPerformanceCounter这两个API来实现
///<summary>
///获取时间精度
///</summary>
///<paramname=\"PerformanceFrequency\"></param>
///<s></s>
[SuppressUnmanagedCodeSecurity]
[DllImport(\"kernel32\")]
privateexternboolQueryPerformanceFrequency(reflongPerformanceFrequency);
///<summary>
///获取时间计数
///</summary>
///<paramname=\"PerformanceCount\"></param>
///<s></s>
[SuppressUnmanagedCodeSecurity]
[DllImport(\"kernel32\")]
privateexternboolQueryPerformanceCounter(reflongPerformanceCount);
下面是完整封装代码:
///<summary>
///定义个高精度时间类
///</summary>
publicTimer
{
#regionprivatemembers
privatelongticksPerSecond=0;
privatelongelapsedTime=0;
privatelongbaseTime=0;
#endregion

#regionwindowsAPI
///<summary>
///获取时间精度
///</summary>
///<paramname=\"PerformanceFrequency\"></param> [Page]
///<s></s>
[SuppressUnmanagedCodeSecurity]
[DllImport(\"kernel32\")]
privateexternboolQueryPerformanceFrequency(reflongPerformanceFrequency);
///<summary>
///获取时间计数
///</summary>
///<paramname=\"PerformanceCount\"></param>
///<s></s>
[SuppressUnmanagedCodeSecurity]
[DllImport(\"kernel32\")]
privateexternboolQueryPerformanceCounter(reflongPerformanceCount);
#endregion

#regionconstructors
///<summary>
///
///</summary>
publicTimer
{
//UseQueryPerformanceFrequencytogetfrequencyofthetimer
(!QueryPerformanceFrequency(refticksPerSecond))
throwApplicationException(\"Timer:PerformanceFrequencyUnavailable\");
Re;


}
#endregion

#regionpublicmethods
///<summary>
///重置时间相关计数器 [Page]
///</summary>
publicvoidRe
{
longtime=0;
QueryPerformanceCounter(reftime);
baseTime=time;
elapsedTime=0;
}
///<summary>
///获取当前和最近次re时间差
///</summary>
///<s>Thetimesincelastre.</s>
publicdoubleGetTime
{
longtime=0;
QueryPerformanceCounter(reftime);
(double)(time-baseTime)/(double)ticksPerSecond;
}
///<summary>
///获取当前系统时间ticks数
///</summary>
///<s>Thecurrenttimeinseconds.</s>
publicdoubleGetAbsoluteTime
{
longtime=0;
QueryPerformanceCounter(reftime);
(double)time/(double)ticksPerSecond;
} [Page]
///<summary>
///获取此次和上次此思路方法两次时间差
///</summary>
///<s>Thenumberofsecondssincelastcallofthisfunction.</s>
publicdoubleGetElapsedTime
{
longtime=0;
QueryPerformanceCounter(reftime);
doubleabsoluteTime=(double)(time-elapsedTime)/(double)ticksPerSecond;
elapsedTime=time;
absoluteTime;
}
#endregion
}
代码:
Timert=Timer;
t.GetAbsoluteTime;
t.GetElapsedTime;
t.Re;
t.GetTime;
需要朋友可以从此处下载
0

相关文章

读者评论

发表评论

  • 昵称:
  • 内容: