Eric
Eric

Reputation: 97591

Alternative to System.DateTime.Now.Ticks in the .NET Micro Framework?

I'm using System.DateTime.Now.Ticks in a time-critical piece of code, and am finding it to be a bottleneck. This is almost certainly due to the overhead of instantiating a DateTime class that goes on behind the scenes.

I was told that I could get this information from System.Environment.TickCount. However, this is in milliseconds, which are too coarse a measurement for what I need. Although this was roughly twice as fast.

Is there some way to get the accuracy of System.DateTime.Now.Ticks without the overhead of constructing System.DateTime.Now?

Upvotes: 2

Views: 4695

Answers (3)

Anthony Wieser
Anthony Wieser

Reputation: 4611

Many microcontrollers have a Real Time Clock which runs of a 32768 Hz crystal, which feeds a ripple timer or a pulse counter built into the hardware.

For instance, this document: http://www.ghielectronics.com/downloads/FEZ/Beginners%20guide%20to%20NETMF.pdf on page 91 describes using a pulse counter on the USBIZI device.

It also links to this document http://www.keil.com/dd/docs/datashts/philips/lpc23xx_um.pdf which on p. 585 describes the TickCounterRegister 6.2.2 Clock Tick Counter Register (CTCR - 0xE002 4004)

So, you should be able to read that register to get a rolling count of 65536 ticks. If your elapsed time is less than a .5 seconds between two reads of that register, a signed subtraction, and adding 65536 if less than 0 will give you the elapsed time.

Upvotes: 4

Icemanind
Icemanind

Reputation: 48686

Eric,

Just so you understand too, when you call the Ticks property of DateTime, what is happening is the .NET framework is converting the date and time (in milliseconds) to a Tick value. In other words, the Tick value you are getting back is not a measurement of time elapsed, but just a conversion of the date time structure, which itself is measured in milliseconds. You may feel like you are getting some high resolution timing by using Ticks, but in reality, milliseconds is as good as you are getting using DateTime anyway. The tick value divides the number of milliseconds elapsed by something like 0x2500 and that is why you are getting a high precision number. But keep in mind that time is still elapsing in milliseconds.

Upvotes: 1

David Nelson
David Nelson

Reputation: 3714

The answer depends on what you need the time for. For example, if you are trying to compare two time instances from the same running instance of your application, then you can try using DateTime.UtcNow, which is not adjusted for locale or DST.

If you need to trigger an event at a specific time, use a Timer (probably System.Threading.Timer if you care that much about the granularity, although System.Timers.Timer is easier to use).

If you need it for some other reason, please specify.

Upvotes: 0

Related Questions