C# 时间(以微秒为单位)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1206367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# time in microseconds
提问by Boris Raznikov
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. I tried using Ticks, but I didn't know how to translate it to microseconds.
我正在搜索如何格式化时间,包括微秒。我正在使用类 DateTime,它允许(使用属性)获取数据直到毫秒,这还不够。我尝试使用 Ticks,但我不知道如何将其转换为微秒。
采纳答案by Jon Skeet
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;
回答by Josip Medved
"ffffff" is what you need.
“ffffff”就是你所需要的。
return DateTime.Now.ToString("HH:mm:ss.ffffff");
回答by Fredrik Karlsson Peraldi
I was unable to get Johns tick to micorosecond conversion to work. Here is how I was able to measure Microsecond and Nanosecond resolution by using ticks and the Stopwatch:
我无法让 Johns 勾选微秒转换来工作。以下是我如何使用刻度和秒表来测量微秒和纳秒分辨率:
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)");