【发布时间】:2021-11-26 11:57:04
【问题描述】:
在我不断尝试学习 C 语言的过程中,我遇到了以下挫折。我正在尝试编写一个函数,以秒为单位返回时间,但精度为毫秒,类似于 Python time.time()。这是我为实现此目的而编写的代码:
#include <stdio.h>
#include <time.h>
float getTime() {
// Get the time in seconds (with millisecond precision), e.g. 1656535840.1737888
// Get spec
struct timespec spec;
// Put the current time (ns) into spec
clock_gettime(CLOCK_REALTIME, &spec);
// Get the time and
// Jam them together to one float and return
return ((float) time(NULL)) + (((float) spec.tv_nsec) / 1000000000.0f);
}
int main() {
// Get the time
float test = getTime();
// Print it to the screen
printf("\nAssignment: %f", test);
// Let's try and make a (pretty bad) clock...
// Loop...
for (int i = 0; i < 30; i ++) {
// Print current time
printf("\nPrinting: %f", getTime());
}
return 0;
}
由于没有sleep()某种命令,计算机应该用字符串"Assignment: "将当前时间打印到屏幕上,然后立即用字符串"Printing: "继续打印时间。因此,它应该打印如下内容:
Assignment: 1633513113.776543
Printing: 1633513113.777353
Printing: 1633513113.778350
Printing: 1633513113.779347
Printing: 1633513113.779347
奇怪的是,它会打印以下内容:
Assignment: 1633513088.000000
Printing: 1633513113.777353
Printing: 1633513113.778350
Printing: 1633513113.779347
Printing: 1633513113.779347
第一行 (Assignment: 1633513088.000000) 的数字与预期的完全不匹配。秒数已关闭(不,两次打印之间没有 25 秒的暂停),毫秒数为 0。我什至不完全确定从哪里开始。如果区别在于将值分配给变量而不是直接打印它,那么我在分配时做错了什么?唉,输出是浮点数,变量test也是浮点数。
出了什么问题,我该如何解决?
【问题讨论】:
-
float类型没有足够的精度,通常约为 7 个十进制数字。请使用double,大约有 16 个。切勿使用float,除非您有特定原因不能使用double。 -
Xiddoc,注意
clock_gettime()不是标准的 C 函数。 -
不方便调用
time()和clock_gettime()。最好使用timespec_get()等1个函数,