Search code examples
.netwindows-cemilliseconds

Windows CE, .NET - how to get CPU ticks or current time in (micro) milliseconds?


I would like to test how difficult are lines of code I wrote. I need to know how long (or how many CPU ticks) it takes to complete them.

I use Windows CE, compact .NET framework 2, VB.NET 2005

On Google and here I found only solutions that work on desktop Windows, not mobile. I tried following:

Private Declare Function GetTickCount Lib "kernel32" () As Long
'and
Private Declare Function GetTickCount Lib "coredll.lib" () As Long
Dim lngStart As Long = GetTickCount() 'did not work

System.Diagnostics.Stopwatch ' does not exist

System.DateTime.Now() ' resolution only seconds I need at least milliseconds

System.Environment.TickCount ' same as Now()

(DateTime.Now-new DateTime(1970,1,1)).TotalMilliseconds ' only seconds

... and much more. Nothing worked.

Can you help please?


Solution

    1. The GetTickCount API returns a DWORD, which is a 32-bit integer. That corresponds to a managed Integer not a Long so that's explains the P/Invoke failure.
    2. DateTime.Now just calls the GetSystemTime API which, in every CE device I've used since back in the 2.0 days, did not have millisecond resolution. Now the OEM of any device could give it ms resolution, but I've never seen it (well I saw it once in an OS that I built for a customer who specifically wanted it). A resonable workaround can be found here.
    3. Environment.TickCount calls the GetTickCount API, which typically returns milliseconds since the processor started, with a wrap at something like 22 days. It is not processor ticks. It is much slower.
    4. Some devices support a higher-resolution counter, which can be queried by P/Invoking QueryPerformanceFrequency and QueryPerformanceCounter to get (obviously) the frequency and current value. This often has a hns (hundreds of nanoseconds) resolution. Though if you're concerned about things at this level, I might begin to question your choice of managed code. At any rate, an example for this can be found here.
    5. If you're looking at code performance and the CF then this article, while a bit old, is still valid and informative.

    EDIT

    Since you mentioned the Stopwatch class in your question:

    1. There's an implementation of the Stopwatch class that works with CF 1.0 and CF 2.0 in the old 1.x SDF source code. You can download the full (free) 1.4 source here (bottom middle of the page).