如何在c#中获得微秒 [英] How to get Microseconds in c#
问题描述
大家好,
我必须在日志文件中添加日志。要做到这一点,我必须在文本中包含微秒的日期时间。
时间戳的格式应为HH:MM:SS:MilliSeconds:MicroSeconds
For例如:
12:35:17:234:212 - 启动获取数据的功能。
12:35:17:234:451 - 获取数据的功能已完成。
12:35:17:234:600 - 更新数据的功能已启动。
12:35:17:234:754 - 更新数据的功能正在进行中。
12:35:17:234:900 - 更新数据的功能已完成。
12:35:17:235:002 - 流程结束
有没有办法解决这个问题?
我试图包含下面的日志,但它没有不行。在这样的所有日志行中,我得到相同的输出。
Console.WriteLine(DateTime.Now.ToString(< span class =code-string> HH:mm:ss:fff)+(DateTime.Now.Ticks / 10 )。ToString()+ - 获取数据的函数已启动。 );
谢谢&问候,
Mathi。
理论上,你可以用它来写出微秒:Console.WriteLine(DateTime.Now.ToString( HH:mm:ss.ffffff)) ;
但是,根据您的系统硬件和每个日志记录操作的时间成本,您可能无法获得微秒的计时准确性;这是解决方案的问题。请参阅Jon Skeet对此的看法,这是这些评论的来源:[ ^ ]。
幸运的是,CodeProject是你的朋友,这里有两篇关于获得更高分辨率计时准确度的好文章:[ ^ ],[ ^ ]。
一点警告:如果你需要高精度,请不要使用标准的WinForms Timer组件:而是使用其他一个Timers,如System.Timers.Timer。
你可以使用 ffffff以格式字符串表示微秒:
Console.WriteLine(DateTime.Now.ToString(HH:mm:ss.ffffff));
到将 的数字转换为至微秒,只需使用:
< pre lang = c#> long microseconds = ticks /(TimeSpan.TicksPerMillisecond / 1000 );
如果这些对您没有帮助,请提供有关您正在尝试做什么的更多信息。
Hi All,
I have to add logs in my log files. To do that I have to have Date Time with micro seconds in the along with the Text.
The time stamp should in the format of HH:MM:SS:MilliSeconds:MicroSeconds
For Ex:
12:35:17:234:212 - The function to fetch data started.
12:35:17:234:451 - The function to fetch data Completed.
12:35:17:234:600 - The function to update data started.
12:35:17:234:754 - The function to update data is in progress.
12:35:17:234:900 - The function to update data completed.
12:35:17:235:002 - End of Process
Is there any way to handle this?
I tried to include logs like below but it didn't work. In all the log lines like this I'm getting the same output.
Console.WriteLine(DateTime.Now.ToString("HH:mm:ss:fff") + (DateTime.Now.Ticks / 10).ToString() + " - The Function to fetch data started.");
Thanks & Regards,
Mathi.
In theory, you can use this to write out micro-seconds:Console.WriteLine(DateTime.Now.ToString("HH:mm:ss.ffffff"));But, depending on your system hardware, and the time-cost of each logging operation, you may not be able to get microsecond timing accuracy; that's a problem of "resolution." See Jon Skeet's take on this which is the source of these comments: [^].
Fortunately, CodeProject is your friend and there are two good articles here on getting higher resolution timing accuracy: [^], [^].
One caution: do not use the standard WinForms Timer component if you need high accuracy: instead use one of the other Timers, like System.Timers.Timer.
You can use "ffffff" in a format string to represent microseconds:
Console.WriteLine(DateTime.Now.ToString("HH:mm:ss.ffffff"));
To convert a number of ticks to microseconds, just use: <pre lang="c#">long microseconds = ticks / (TimeSpan.TicksPerMillisecond / 1000);
If these don't help you, please provide more information about exactly what you're trying to do.
这篇关于如何在c#中获得微秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!