Thom Lv
Thom Lv

Reputation: 111

Get system clock/time in C# without using any objects?

I'm developing an application in C# that requires many function calls (100-1000 per second) to happen at very specific times. However, there are extremely tight specs on the latency of this application, and so due to the latency increase associated with garbage collection, it's not feasible for me to use DateTime or Timer objects. Is there some way I can access the system time as a primitive type, without having to create DateTime objects?

TL;DR: Is there an analogue for Java's System.currentTimeMillis() for C#?

Upvotes: 0

Views: 1364

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499770

What makes you think DateTime allocates objects? It's a value type. No need for a heap allocation, and thus no need for garbage collection. (As TomTom says, if you have hard latency requirements, you'll need a real-time operating system etc. If you just have "low" latency requirements, that's a different matter.)

You should be able to use DateTime.Now or DateTime.UtcNow without any issues - UtcNow is faster, as it doesn't perform any time zone conversions.

As an example, I just time 100 million calls to DateTime.UtcNow and then using the Hour property, and on my laptop that takes about 3.5 seconds. Using the Ticks property (which doesn't involve as much computation) takes about 1.2 seconds. Without using any property, it only takes 1 second.

So basically if you're only performing 1000 calls per second, it's going to be irrelevant.

Upvotes: 5

TomTom
TomTom

Reputation: 62093

Consider not using windows. SImple like that. Not even "not using C#" but not using windows.

However, there are extremely tight specs on the latency of this application,

There are special real time operating systems that are build for exactly this.

Is there an analogue for Java's System.currentTimeMillis() f

Yes. but that still will not help.

The best you CAN do is high precision multimedia timers, which work like a charm but also have no real time guarantees. The language is not hte problem - your OS of choicee is unsuitable for the task at hand.

GC is totally not an issue if programming smart. Objects are not an issue, usin a concurrent GC and avoiding EXCESSIVE creation of objects helps a lot. You dramatize a problem here that is not there to start with.

There is a kernel API that can handle very low MS precision and can be accessed from C#

http://www.codeproject.com/Articles/98346/Microsecond-and-Millisecond-NET-Timer

the real problem is you must reconfigure the kernel to make that interrupt at short notices or you are at the mercy of the scheduler that does not ahve such a low resolution.

Upvotes: 0

Related Questions