C# 亚毫秒计时

发布于 2024-08-21 01:56:49 字数 188 浏览 4 评论 0原文

C# 中是否有地方可以执行亚毫秒精度的计时操作?我将计时代码放入我的软件中,所有内容都以 0ms 的形式返回。我想知道是否有办法获得更细的粒度。

附录:这是获得亚毫秒计时的正确代码吗?

timeSpan.TotalMilliseconds / 10

我仍然得到 0 作为经过时间

Is there anywhere in C# to perform timing operations with sub millisecond accuracy? I'm putting timing code in my software and everything is being returned as 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

江心雾 2024-08-28 01:56:49

您始终可以尝试使用 QueryPerformanceCounterStopWatch 托管方法类

You could always try using QueryPerformanceCounter or the StopWatch class for a managed approach

嗳卜坏 2024-08-28 01:56:49

使用 System.Diagnostics.Stopwatch

Use System.Diagnostics.Stopwatch

梦幻的心爱 2024-08-28 01:56:49

通常我会通过多次重复操作来测量此类场景(尽可能多地获得几十或几百毫秒的毫秒数)。

然后您可以更轻松地调整和测量。

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.

猫腻 2024-08-28 01:56:49

您可以尝试以 Ticks 而不是毫秒来衡量您的性能。在性能方面它将更加准确。

但我同意 Sam 和 Tyranid 的观点,使用 System.Diagnostics.StopWatch。

You could try measuring your performance in matter of Ticks instead of milliseconds. It will be much more accurate in terms of performance.

but I agree with Sam and Tyranid, use System.Diagnostics.StopWatch.

依 靠 2024-08-28 01:56:49

我学到了一些新东西。这些蜱虫确实很方便。完整的示例:

Stopwatch stopwatch = Stopwatch.StartNew();

// Run code to get duration of

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

您还可以在 Console.WriteLine 中使用 stopwatch.ElapsedTicks ,但我不知道这是否有任何性能延迟,这就是为什么我首先检索它并放入它在一个变量中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文