[Mono-list] Bug in Environment.TickCount

Will Murnane will.murnane at gmail.com
Fri Jul 20 00:27:35 EDT 2007

There doesn't seem to be a good way to do this on Linux.  The sysctl()
call for 'uptime' only works on *BSD, apparently.  However, that's not
to say there's *no* way to do it:
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/sysctl.h>
int main(void)
/*      int mib[2], uptime;
        mib[0] = CTL_KERN;
        mib[1] = KERN_BOOTTIME;
        size_t len;                             // Note: this doesn't
work on Linux.  Oh well.
        sysctl(mib, 2, &uptime, &len, NULL, 0);
        printf("Uptime = %lds\n", uptime); */
        FILE* fd = fopen("/proc/uptime", "r");
        float uptime;
        fscanf(fd, "%f", &uptime);
        printf("Uptime = %ld ms\n", (int)(uptime * 1000));

However, note that the precision of the timer that uses is the same as
the timer your kernel uses, so when I run it twenty times as fast as
possible, I get this:
for i in `seq 1 20`; do ./uptime; done
Uptime = 866848750 ms
(five more times, exactly the same time)
Uptime = 866848812 ms
(same time a bunch more)
That tells me that on this system the clock only ticks about 16 times
a second.  Ouch.

You may be able to simulate something higher-res using gettimeofday()
or the DateTime equivalent, but it won't necessarily be monotone.
With network latency and so forth 62ms resolution might be good
enough... but otherwise, you could use time since your program started
as your "uptime".  Would that suffice?


On 7/19/07, Thiago M. Sayão <thiago.sayao at gmail.com> wrote:
> Hello!
> Enrironment.TickCount is supposed to return the miliseconds since the
> boot. For my surprise it was returning a negative number which should
> only happen on the 47th day of uptime.
> I did i fix (attached) but it doesn't seem 100% correct and i am not
> sure if it would work after some days.
> Since i'm coding a msn library and msn p2p protocol uses GetTickCount(),
> it's messing things for me!
> Can anyone take a look?
> Thanks!
> _______________________________________________
> Mono-list maillist  -  Mono-list at lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-list

More information about the Mono-list mailing list