Ent*_*ity 114 c# datetime time-precision milliseconds
我正在制作一个程序,我需要在几毫秒内获得时间.到时候,我的意思是一个永远不会与自己相等的数字,并且总是比一秒钟前更大的1000个数字.我已经尝试过转换DateTime.Now为a TimeSpan并TotalMilliseconds从中得到...但我听说它并不完全准确.
有更简单的方法吗?
Eva*_*ski 283
long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
Run Code Online (Sandbox Code Playgroud)
这实际上是如何在类中实现各种Unix转换方法DateTimeOffset(.NET Framework 4.6 +,.NET Standard 1.3+):
long milliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();
Run Code Online (Sandbox Code Playgroud)
Red*_*ter 77
使用该Stopwatch课程.
提供一组方法和属性,可用于准确测量经过的时间.
这里有一些很好的信息来实现它:
性能测试:使用System.Diagnostics.Stopwatch进行精确的运行时测量
Ita*_*aro 13
该DateTime.Ticks属性获取表示日期和时间的刻度数.
10,000蜱是一毫秒(每秒10,000,000蜱).
我使用以下课程.我在互联网上发现了一次,假设是最好的NOW().
/// <summary>Class to get current timestamp with enough precision</summary>
static class CurrentMillis
{
private static readonly DateTime Jan1St1970 = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>Get extra long current timestamp</summary>
public static long Millis { get { return (long)((DateTime.UtcNow - Jan1St1970).TotalMilliseconds); } }
}
Run Code Online (Sandbox Code Playgroud)
来源不明.
您可以尝试本QueryPerformanceCounter机方法.有关更多信息,请参见http://www.pinvoke.net/default.aspx/kernel32/QueryPerformanceCounter.html.这是Stopwatch班级使用的.
请参见如何在.NET/C#中获取tick精度的时间戳?欲获得更多信息.
Stopwatch.GetTimestamp() 可以访问此方法:
public static long GetTimestamp() {
if(IsHighResolution) {
long timestamp = 0;
SafeNativeMethods.QueryPerformanceCounter(out timestamp);
return timestamp;
}
else {
return DateTime.UtcNow.Ticks;
}
}
Run Code Online (Sandbox Code Playgroud)
我使用了DateTime.Now.TimeOfDay.TotalMilliseconds(当前日期),希望对您有所帮助。