Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix Time - nanoseconds?

I'm current using this method (C#) to get the Unix Time in milliseconds:

long UnixTime()
{
    return (long) (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds;
}   

Question - Is there a way to get the unix time in nanoseconds?

Thanks in advance.

like image 401
Acidic Avatar asked Oct 25 '25 23:10

Acidic


2 Answers

The calculation by itself isn't hard:

long UnixTime()
{
    DateTime epochStart=new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return (DateTime.UtcNow - epochStart).Ticks*100;
}

DateTime and TimeSpan internally store an integral amounts of ticks, with one tick being 100ns. I also specified the epoch start as UTC time, because I consider it ugly to subtract DateTimes with different Kind, even if it works.

But DateTime.UtcNow has very low accuracy. It is only updated every few milliseconds(Typical values vary between 1ms and 16ms).


To get a constant framerate you could use StopWatch since you don't need the absolute time. But if you go that way you must use a busy wait. Since Thread.Sleep, timers,... suffer from the same limitation.

Alternatively you can use the timeBeginPeriod(1) API, to force windows to update the clock and run timers every 1ms. But this is a global setting and increases power consumption. Still it's better than busy-wait.

To measure time differences you can use StopWatch with is based on QueryPerformanceCounter, but this comes with its own set of problems, such as desyncs between different cores. I've seen machines were QueryPerformanceCounter jumped by several hundred Milliseconds when your thread gets scheduled on another core.

like image 112
CodesInChaos Avatar answered Oct 28 '25 16:10

CodesInChaos


The TotalMilliseconds property returns a double containing whole and fractional milliseconds.

So, you only have to multiply its value by 1000000 to obtain nanoseconds:

return (long) ((DateTime.UtcNow
    - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds * 1000000.0);
like image 23
Frédéric Hamidi Avatar answered Oct 28 '25 16:10

Frédéric Hamidi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!