Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent of "gettimeofday" in .NET

Tags:

c#

I am working with .NET but I need to communicate with a logging service, unix based, that expects seconds and microseconds since the Unix epoch time. The seconds is easily retrievable doing something like:

DateTime UnixEpoch = new DateTime(1970, 1, 1);
TimeSpan time = DateTime.UtcNow() - UnixEpoch
int seconds = (int) time.TotalSeconds

however, I am unsure how to calculate the microseconds. I could use the TotalMilliseconds property and convert it to microseconds but I believe that defeats the purpose of using microseconds as a precise measurement. I have looked into using the StopWatch class but it doesn't seem like I can seed it with a time (Unix Epoch for example).

Thanks.

like image 531
PolandSpring Avatar asked Jan 31 '11 22:01

PolandSpring


3 Answers

Use the Ticks property to get the most fine-grained level of detail. A tick is 100ns, so divide by 10 to get to microseconds.

However, that talks about the representation precision - it doesn't talk about the accuracy at all. Given the coarse granularity of DateTime.UtcNow I wouldn't expect it to be particularly useful. See Eric Lippert's blog post about the difference between precision and accuracy for more information.

You may want to start a stopwatch at a known time, and basically add its time to the "start point". Note that "ticks" from Stopwatch doesn't mean the same as TimeSpan.Ticks.

like image 99
Jon Skeet Avatar answered Nov 08 '22 19:11

Jon Skeet


From Epoch Converter:

epoch = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;

This will truncate it because of integer division, so make it 10000000.0 to maintain the sub-second portion, or just don't do the division.

It's important to note that the .Ticks property you get is relative to Jan 1, 0001 and not Jan 1, 1970 like in UNIX which is why you need to subtract that offset above.

edit: just for clarity, that nasty constant is just the number of ticks between Jan 1, 0001 and Jan 1, 1970 in UTC. If you take the seconds portion of it (62135596800) and divide by (365 * 24 * 60 * 60) you see you get a number close to 1970, which is of course not exactly 1970 due to leap adjustments.

like image 41
Daniel DiPaolo Avatar answered Nov 08 '22 18:11

Daniel DiPaolo


DateTime.Ticks represent units of 100 nanoseconds since Jan. 1, 0001.

like image 42
Mark Avenius Avatar answered Nov 08 '22 19:11

Mark Avenius