C# time in microseconds

后端 未结 4 1341
一个人的身影
一个人的身影 2020-11-30 05:18

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 trie

相关标签:
4条回答
  • 2020-11-30 05:53

    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:

    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)");
    
    0 讨论(0)
  • 2020-11-30 05:54

    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:

    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:

    const long TicksPerMicrosecond = 10;
    
    ...
    
    long microseconds = ticks / TicksPerMicrosecond;
    
    0 讨论(0)
  • 2020-11-30 05:57

    "ffffff" is what you need.

    return DateTime.Now.ToString("HH:mm:ss.ffffff");
    
    0 讨论(0)
  • 2020-11-30 06:08

    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.

    0 讨论(0)
提交回复
热议问题