早上好!
我正在尝试从timeval结构中获取纳秒级时间戳(uint64_t)。
struct timeval t;
// initialized so that ....
print("t sec: %ld, micro sec: %ld", t.tv_sec, t.tv_usec);
// .... prints "t sec: 4, micro sec: 130728"
long int sec = (long int) t.tv_sec;
// just did that because I thought that using time_t in calculations may cause errors
// print("%ld", sec) -> 4, so this seems to work as expected
uint64_t t_int = (sec * 1000000 + t.tv_usec) * 1000; // should be nanoseconds
print("t_int (uint64_t) %llu", t_int);
// prints "t_int (uint64_t) 18446744073545312320"
我的timevals应该绝对适合uint64_t。此外,从time_t转换为long int的强制转换有效,因此我所做的只是使用两个long int进行简单计算,将结果放入uint64_t中,所以我不确定为什么会得到明显错误的值。有什么想法吗?这只是格式化错误的一种错误方式(使用%llu)吗?
long int
的大小是多少?你得到的sec
的值是多少?你是否意识到你的计算sec * 1000000
是使用的long int
而不是uint64_t
?还有该代码片段中的所有其他计算都是如此。 - Gerhardht_int
打印为整数:printf("t_int (uint64_t) %"PRIu64,t_int);
。请参见此处。 - Gerhard