获得高精度时间

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

22            else
23            {
24                _f = -1;
25            }

26        }

27        if (f == -1)
28        {
29            return Environment.TickCount * 10000;
30        }

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

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

50
51        return new DateTime(_tc + GetTickCount());
52    }

53}

54
原文地址:https://www.cnblogs.com/FlyFire/p/349965.html