Domanda

/*
 * Returns time in s.usec
 */
float mtime()
{
    struct timeval stime;
    gettimeofday(&stime,0x0);
    return (float)stime.tv_sec+((float)stime.tv_usec)/1000000000;
}

main(){
    while(true){
        cout<<setprecision(15)<<mtime()<<endl;
        // shows the same time irregularly for some reason and can mess up triggers
        usleep(500000);
    }
}

Why does it show the same time irregularly? (compiled on ubuntu 64bit and C++) What other standard methods are available to generate a unix timestamp with millisecond accuracy?

È stato utile?

Soluzione

A float has between 6 and 9 decimal digits of precision.

So if integer part is e.g. 1,391,432,494 (UNIX time when I write this; requiring 10 digits), you're already out of digits for the fractional part. Not so good, and this is why float is failing for this.

Jumping to double gives you 15 digits so it seems to suffice as long as you can assume that the integer part is a UNIX timestamp, i.e. seconds since 1970 since that means it's not likely to use drastically more digits any time soon.

Altri suggerimenti

Seems float doesn't have enough precision, replaced with double and all is ok now.

/*
 * Returns time in s.usec
 */
double mtime()
{
    struct timeval stime;
    gettimeofday(&stime,0x0);
    return (double)stime.tv_sec+((double)stime.tv_usec)/1000000000;
}

Still don't exactly understand the reason for the random behavior... PS. I was capturing a mtime() and comparing it with current time to get duration.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top