gettimemillis function give negative values..

I'm writing a program on a raspberry pi, the millis function has been working correctly for days, today it started giving negative value, how can I fix it?

static tmillis_t GetTimeInMillis() {
struct timeval tp;
gettimeofday(&tp, NULL);
return tp.tv_sec * 1000 + tp.tv_usec / 1000;
What's your definition of tmillis_t? It should be an unsigned value, but is probably signed.
Last edited on
typedef int64_t tmillis_t; my retarded variables :D
int64_t is a signed type. Signed types as you've found out allow for negative values. You don't want negative values use uint64_t.

But that could result in value underflow/overflow problems.
Apparently he tries to convert the timeval struct into a scalar milliseconds value.

...because tv_sec (seconds) is multiplied by 1000 and tv_usec (microseconds) is divided by 1000.

Even if time is counted in milliseconds (from Epoch), then a signed int64_t should be way large enough to not "wrap around" into negative area – anytime soon. So I suspect something with the computation goes wrong.

Provided that tmillis_t is really an alias for int64_t (why not use just int64_t?), try this conversion:
return (((tmillis_t)tp.tv_sec) * 1000LL) + (((tmillis_t)tp.tv_usec) / 1000LL);
Last edited on
Registered users can post here. Sign in or register to post.