【发布时间】:2014-05-22 08:26:01
【问题描述】:
double GetTimeStamp()
{
struct timespec start;
if((clock_gettime( CLOCK_MONOTONIC, &start)) == -1 )
{
perror("clock gettime\n");
}
return start.tv_sec + start.tv_nsec * 1e-9; //seconds
}
MAIN.c:
uint64_t Receive;
uint32 receiveTime;
int main()
{
rc=recvfrom(sock, buf, 256, 0, (struct sockaddr*) &client, &len);
Receive = GetTimeStamp();
receiveTime = (uint32) (Receive / 1000000); // I am converting to microseconds
printf("Receive time: %lu\n", receiveTime);
}
我正在获取时间戳并从另一个程序中读取该时间,如上所示。但是,如果我按照上述方式进行操作,我将得不到任何价值。为什么 main 中没有显示任何值?
【问题讨论】:
-
您确实转换为 int,这确实切断了小数点后的所有内容。所以如果你有 1 秒 ->
(int)(1/ 100000) = 0 -
那么解决方案是什么? double 将是一个非常大的值。
-
哦,我刚刚注意到你的转换还是很糟糕。 nano_seconds 到秒是
nano_seconds / 1e-9;,秒到微秒是:seconds * 1e6 -
如果你真的想打印你实际拥有的东西:
double receiveTime = 1.000000555; printf("Receive time: %0.8f\n", receiveTime) -
1) 虽然我怀疑这是你的问题,
printf("Receive time: %lu\n", receiveTime);是 UB。应该是printf("Receive time: %" PRIu32 "\n", receiveTime);。 2) 确定代码从recvfrom()返回?
标签: c linux timestamp clock qnx