简体   繁体   English

C# 时间(以微秒为单位)

[英]C# time in microseconds

I am searching how to format time including microseconds.我正在搜索如何格式化时间,包括微秒。 I'm using class DateTime, it allowes (using properties) to get data till miliseconds, which is not enougth.我正在使用类 DateTime,它允许(使用属性)获取数据直到毫秒,这还不够。 I tried using Ticks, but I didn't know how to translate it to microseconds.我尝试使用 Ticks,但我不知道如何将其转换为微秒。

You can use "ffffff" in a format string to represent microseconds:您可以在格式字符串中使用"ffffff"来表示微秒:

Console.WriteLine(DateTime.Now.ToString("HH:mm:ss.ffffff"));

To convert a number of ticks to microseconds, just use:要将刻度数转换为微秒,只需使用:

long microseconds = ticks / (TimeSpan.TicksPerMillisecond / 1000);

If these don't help you, please provide more information about exactly what you're trying to do.如果这些对您没有帮助,请提供有关您正在尝试做什么的更多信息。

EDIT: I originally multiplied ticks by 1000 to avoid losing accuracy when dividing TimeSpan.TicksPerMillisecond by 1000. However, It turns out that the TicksPerMillisecond is actually a constant value of 10,000 - so you can divide by 1000 with no problem, and in fact we could just use:编辑:我最初将ticks乘以 1000 以避免在将TimeSpan.TicksPerMillisecond除以 1000 时失去准确性。然而,事实证明, TicksPerMillisecond实际上是 10,000 的常数值 - 所以你可以毫无问题地除以 1000,事实上我们可以只使用:

const long TicksPerMicrosecond = 10;

...

long microseconds = ticks / TicksPerMicrosecond;

I was unable to get Johns tick to micorosecond conversion to work.我无法让 Johns 勾选微秒转换来工作。 Here is how I was able to measure Microsecond and Nanosecond resolution by using ticks and the Stopwatch:以下是我如何使用刻度和秒表来测量微秒和纳秒分辨率:

Stopwatch sw = new Stopwatch();
sw.Start();

// Do something you want to time

sw.Stop();

long microseconds = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L*1000L));
long nanoseconds = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L*1000L*1000L));

Console.WriteLine("Operation completed in: " + microseconds + " (us)");
Console.WriteLine("Operation completed in: " + nanoseconds + " (ns)");

“ffffff”就是你所需要的。

return DateTime.Now.ToString("HH:mm:ss.ffffff");

It's:它的:

return DateTime.Now.ToString("HH:mm:ss.ffffff");

for the whole time stamp in format hours:minutes:seconds:microseconds格式为小时:分钟:秒:微秒的整个时间戳

return DateTime.Now.ToString(".ffffff");

if you need only residual microseconds.如果您只需要剩余微秒。

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

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