gpt4 book ai didi

c - C 中的 long 减法会失去精度?

转载 作者:行者123 更新时间:2023-11-30 18:47:56 26 4
gpt4 key购买 nike

我确信答案很简单,但我不太明白。我正在尝试使用以下代码计算两个 struct timespec 之间的增量:

struct timespec start, finish, diff;
int ndiff;

/* Structs are filled somewhere else */

diff.tv_sec = finish.tv_sec - start.tv_sec;
ndiff = finish.tv_nsec - start.tv_nsec;
if (ndiff < 0) {
diff.tv_sec--;
ndiff = 1L - ndiff;
}
diff.tv_nsec = ndiff;

printf("Elapsed time: %ld.%ld seconds.\n", diff.tv_sec, diff.tv_nsec);

但是,输出总是类似于 Elapsed time: 0.300876000 秒。 这似乎表明我丢失了纳秒的最后三位数字(因为这些数字不应始终为零) 。有人能指出是什么原因造成的吗?

最佳答案

Elapsed time: 0.300876000 seconds. which seems to indicate that I'm losing the last three digits of the nanoseconds (since those shouldn't always be zero). Can someone point out what's causing that?

代码的时钟报告精度为 1000 ns。 @John Bollinger @rici

和/或

diff.tv_sec 不一定是long。使用匹配的说明符。

// printf("Elapsed time: %ld.%ld seconds.\n", diff.tv_sec, diff.tv_nsec);
// Also insure fraction is printed with 9 digits
printf("Elapsed time: %lld.%09ld seconds.\n", (long long) diff.tv_sec, diff.tv_nsec);
<小时/>

此外,更新 ndiff 时“借用”数学不正确。

ndiff = finish.tv_nsec - start.tv_nsec;
if (ndiff < 0) {
diff.tv_sec--;
// ndiff = 1L - ndiff;
ndiff += 1000000000;
}

更好的是,删除 int diff 变量。

diff.tv_sec = finish.tv_sec - start.tv_sec;
diff.tv_nsec = finish.tv_nsec - start.tv_nsec;
if (diff.tv_nsec < 0) {
diff.tv_sec--;
diff.tv_nsec += 1000000000;
}
<小时/>

如果finish发生在start之前,那么可能需要其他代码来保持diff的2个成员具有相同的符号。

关于c - C 中的 long 减法会失去精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47146673/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com