WindowsCEデバイスで、ミリ秒単位の時間を取得する方法

最近至極いい加減に開発系ネタをPickupさせて頂いてますが、ついでにこのエントリーもその流れにのって(^^;

One seemingly strange behavior that Windows CE devices (including Pocket PC, Smartphone and Windows Mobile devices) exhibit is that when you query the device time, you get back either a zero of some constant but invalid value for the milliseconds field. This is true whether you call GetLocalTime or GetSystemTime in native code or DateTime.Now in managed code. Why is it that devices running an OS that has real-time capabilities can’t provide us as developers with a clock that has simple millisecond resolution? The answer lies not in the OS ? which is quite capable of giving that resolution ? but in how the time function is implemented by the device OEM.

Typically Windows CE devices contain a piece of hardware internally called a real time clock or RTC. The RTC is very accurate, but often has a resolution of only 1 second. When the OS was implemented, most OEMs simply return the value that the RTC holds and therefore when you query the time that’s all you get.

So the question remains ? how can we as developers get a millisecond-resolution time? If you’re simply looking to get the time short tasks take, then often calling GetTickCount or Environment.TickCount (which is the number of milliseconds since the OS started and tied to a separate oscillator in the processor) is sufficient, but what if we want a true time stamp with a millisecond field? The answer is that we simply have to calculate it. In this white paper we’ll look at code that does that calculation and to make our code reusable, we’ll create a simple class called DateTime2 that will expose a Now property that has millisecond resolution.