Measuring Time

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi!

What is the best way to measure time in .NET cf? I currently use:

DateTime start = DateTime.Now;
// Do some work
double elapsed = (DateTime.Now - start).TotalMilliseconds;

This doesn't seem to work very well, as it always returns 0.0 or 1000.0. I
need a better measurement. Any suggestions?

Thanks in advance!
Nille
 
DateTime class in CF is accurate up to 1 sec. Use either
Environment.TickCount or PInvoke QueryPerformanceCounter
 
Actually to be technical, I don't think the CF is limited here - I mean it
has a milliseconds member, so I *assume* (yes, I know about assumptions)
that it simply returns the millisecond value retrieved by GetLocalTime. Of
course that member in most CE devices returns either zero or an invalid
number becasue it's not so easy to get a sub-second time interval along with
the hrs/mins/secs, but there's nothing that says an OEM can't implement it
(I did it as a test on a platform before and it worked reasonably well).

So to be totally correct, assuming my assumptions were correct (and that's a
lot of assuming) then the milliseconds member of the DateTime returned by
properties such as Now is dependent on the OEM implementation of the
SystemTime and is very often not implemented, which means that it is most
often useless and one should use Environmet.Tickcount to get time spans.
However if you need an actual millisecond resolution time for something like
data logging, check with your OEM, it may in fact be possible.

I just had to put that out there because it seems that lately I've been
getting called out on exceptions to the rule (like USB Host not being
available on Pocket PC) and because I know you can take it. :)

-Chris
 
You can also use P/Invoke to query the OS performance timer.
It is the finest time accuracy you can obtain on Windows.

[DllImport("coredll.dll")]
public static extern int QueryPerformanceCounter(ref double Counter);

[DllImport("coredll.dll")]
public static extern int QueryPerformanceFrequency(ref double Frequency);

double BeginTime = 0;
double EndTime = 0;
double Frequency = 0;
double Elapsed = 0;

QueryPerformanceFrequency(ref Frequency);
QueryPerformanceCounter(ref BeginTime);
//Do Something
QueryPerformanceCounter(ref EndTime);
Elapsed = (EndTime - BeginTime) / Frequency;

Hope this helps!


Louis-Pierre Beaumont
 
Back
Top