2

In my project I'm using struct timespec as follows

struct timespec start, end;
clock_gettime(CLOCK_REALTIME,&start);
/* Do something */
clock_gettime(CLOCK_REALTIME,&end);

It returns a value as ((((unsigned64)start.tv_sec) * ((unsigned64)(1000000000L))) + ((unsigned64)(start.tv_nsec))))

Can anyone tell why we are using the unsigned64 format and also help me understand this structure in detail?? I'm using this code in my study about time calculation in nanoseconds precision for the code execution time taken

4

1 回答 1

1

无符号 32 位类型(如unsigned int现代平台上)的最大值略高于 40 亿。如果您有 5 并将其乘以 10 亿(就像在问题中的代码中所做的那样),您将得到 50 亿的值,大于 32 位无符号类型中可以包含的值。输入 64 位类型,它可以容纳更高的值(18446744073709551615准确地说,与无符号的 32 位最大值仅比较4294967295)。


顺便说一句,代码可以简化为

start.tv_sec * 1000000000ULL + start.tv_nsec

这种简化是可能的,因为编译器会根据需要自动将低精度类型和值转换为高精度。由于您在表达式中有一个unsigned long long(这就是ULL意思)文字值,因此表达式的其余部分也将被转换为unsigned long long并且结果将是 type unsigned long long

于 2014-02-05T09:07:14.150 回答