获得高精度时间

本文介绍了一种使用C#实现的高精度计时方法,通过调用内核API获取系统频率和计数来实现更精确的时间测量。此外,还提供了一个GetExactNow方法用于获取当前时间,并减小了与DateTime.Now之间的偏差。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1None.gifusing System;
 2None.gifusing System.Runtime.InteropServices;
 3None.gifpublic class A
 4ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 5InBlock.gif    [DllImport("kernel32.dll")]
 6InBlock.gif    static extern bool QueryPerformanceCounter([In, Out] ref long lpPerformanceCount);
 7InBlock.gif    [DllImport("kernel32.dll")]
 8InBlock.gif    static extern bool QueryPerformanceFrequency([In, Out] ref long lpFrequency);
 9InBlock.gif
10InBlock.gif    static long _f = 0;
11InBlock.gif
12InBlock.gif    static public long GetTickCount()
13ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
14InBlock.gif        long f = _f;
15InBlock.gif
16InBlock.gif        if (f == 0)
17ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
18InBlock.gif            if (QueryPerformanceFrequency(ref f))
19ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
20InBlock.gif                _f = f;
21ExpandedSubBlockEnd.gif            }

22InBlock.gif            else
23ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
24InBlock.gif                _f = -1;
25ExpandedSubBlockEnd.gif            }

26ExpandedSubBlockEnd.gif        }

27InBlock.gif        if (f == -1)
28ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
29InBlock.gif            return Environment.TickCount * 10000;
30ExpandedSubBlockEnd.gif        }

31InBlock.gif        long c = 0;
32InBlock.gif        QueryPerformanceCounter(ref c);
33InBlock.gif        return (long)(((double)c) * 1000 * 10000 / ((double)f));
34ExpandedSubBlockEnd.gif    }

35InBlock.gif
36InBlock.gif    //GetTickCount()为0时的DateTime.Ticks值
37InBlock.gif    static long _tc = 0;
38InBlock.gif
39InBlock.gif    //这个返回的不是真正的精确时间,但时间与时间的差是精确的。
40InBlock.gif    //GetExactNow与DateTime.Now的偏差比DateTime.Now的精度还要小,所以该偏差
41InBlock.gif    static public DateTime GetExactNow()
42ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
43InBlock.gif        if (_tc == 0)
44ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
45InBlock.gif            long tc = GetTickCount();
46InBlock.gif            DateTime dt = DateTime.Now;
47InBlock.gif            _tc = dt.Ticks - tc;
48InBlock.gif            return dt;
49ExpandedSubBlockEnd.gif        }

50InBlock.gif
51InBlock.gif        return new DateTime(_tc + GetTickCount());
52ExpandedSubBlockEnd.gif    }

53ExpandedBlockEnd.gif}

54None.gif

转载于:https://www.cnblogs.com/FlyFire/archive/2006/03/14/349965.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值