简体   繁体   English

C#亚毫秒时序

[英]C# sub millisecond timing

Is there anywhere in C# to perform timing operations with sub millisecond accuracy? C#中是否有任何地方以亚毫秒精度执行定时操作? I'm putting timing code in my software and everything is being returned as 0ms. 我将时间码放在我的软件中,所有内容都以0ms的形式返回。 I would like to know if there is a way of getting even finer granularity. 我想知道是否有一种方法可以获得更精细的粒度。

Addendum: is this the correct code to get sub millisecond timing? 附录:这是获得亚毫秒时序的正确代码吗?

timeSpan.TotalMilliseconds / 10

I'm still getting 0 as the elapsed time 经历的时间我仍然是0

您可以尝试使用QueryPerformanceCounterStopWatch类进行托管方法

使用System.Diagnostics.Stopwatch

Usually I measure these kinds of scenarios by repeating the operation multiple times (as many as needed to get the milliseconds over a few dozen or hundred. 通常我会通过多次重复操作来测量这些类型的场景(根据需要多少来获得几十或几百毫秒)。

Then you can adjust and measure more easily. 然后,您可以更轻松地进行调整和测量。

You could try measuring your performance in matter of Ticks instead of milliseconds. 您可以尝试在Ticks而不是毫秒内测量您的性能。 It will be much more accurate in terms of performance. 它在性能方面会更准确。

but I agree with Sam and Tyranid, use System.Diagnostics.StopWatch. 但我同意Sam和Tyranid,请使用System.Diagnostics.StopWatch。

I learned something new. 我学到了新东西。 Those Ticks are handy indeed. 那些蜱虫确实很方便。 Complete example: 完整的例子:

Stopwatch stopwatch = Stopwatch.StartNew();

// Run code to get duration of

long durationInTicks = stopwatch.ElapsedTicks;
Console.WriteLine($"Duration: {(decimal)durationInTicks / TimeSpan.TicksPerMillisecond:f3}ms");

You can also use stopwatch.ElapsedTicks inside the Console.WriteLine , but I do not know if that has any performance delays, that's why I first retrieve it and put it in a variable. 您还可以使用stopwatch.ElapsedTicks里面Console.WriteLine ,但我不知道是否有任何性能延迟,这就是为什么我第一次检索,并把它放在一个变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM