Take the 2-minute tour ×
#include <ctime>
#include <cstdio>
#include <sys/time.h>
#include <iostream>
using namespace std;

int main() {
    struct timeval tv;
    gettimeofday(&tv, 0);
    unsigned long long int var=tv.tv_sec*1000L+tv.tv_usec/1000L;
    printf("%u%-15u\n", (unsigned int)(var/1000000000), (unsigned int)(var%1000000000));
    return 0;

This thing prints


on my 64 bit machine, but


on my 32 bit server. The second result is evidently clamped to a 32 bit number, but unsigned long long int is 8 bytes on both architectures. Where is the clamping happening then, and why?

share|improve this question
Neither C nor C++ ever take into account how you use a value when deciding how to compute it. That you save the value in an unsigned long long int has no effect on how it is computed. The call of foo will be the same if you do bool x; x = foo(y); or if you do int x; x = foo(y); or float x; x = foo(y); or whatever. –  David Schwartz Jul 1 '12 at 11:57

1 Answer 1

up vote 4 down vote accepted

It is because the width of long is not the same on your 32-bit and 64-bit machines. The type of tv_sec is an arithmetic type, usually1) long.

You can ensure the multiplication is done with a 64-bit type by using 1000ULL instead of 1000L:

unsigned long long int var=tv.tv_sec*1000ULL+tv.tv_usec/1000ULL;

1) On glibc for example, it is long. "In the GNU C library, time_t is equivalent to long int" http://www.gnu.org/software/libc/manual/html_node/Simple-Calendar-Time.html

share|improve this answer
But tv_sec is not long, it's time_t. –  cnicutar Jul 1 '12 at 11:54
@cnicutar Thanks, updated. –  ouah Jul 1 '12 at 11:56
I was starting from the wrong assumption that the timeval fields were already 64 bits. By the way, where's a list of the possible prefix for integer literals? –  Lorenzo Pistone Jul 1 '12 at 12:11
@LorenzoPistone in C++11, 2.14.3 and in C11, –  ouah Jul 1 '12 at 12:14

Your Answer


