c - 如何使用 float 来设置超时?

标签 c time

我想做一个 while 循环,它会说“Hello World”2 秒 500 毫秒(2.5 秒)。我编写的代码当前适用于普通整数,但如果我将其更改为使用 float ,它将停止工作

有什么想法吗?

损坏的代码:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
    float timeout = time(NULL) + 2.5;

    while(time(NULL) < timeout) {
        printf("Hello World\n");
    }

    return 0;
}

最佳答案

您的代码的问题是:

  1. 您使用 float 来表示 time() 的结果,这是一个大整数,可能会导致转换不准确,因为浮点值的性质。

  2. time() 函数的精度仅精确到秒,因此您的代码永远不会运行 2.5 秒,但始终会运行 3 秒,因为您可以仅以 1 秒的步长进行。

要解决此问题,无需使用浮点值(这没有意义,因为大多数处理时间的函数都使用整数值),您可以使用 gettimeofday() Linux 上的函数,或 GetSystemTime()如果您使用的是 Windows,则可以使用该函数。

Linux:

#include <stdio.h>
#include <sys/time.h>

unsigned long long get_time(void) {
    struct timeval time;
    gettimeofday(&time, NULL);

    return time.tv_sec * 1000 * 1000 + time.tv_usec;
}

int main(int argc, char* argv[]) {
    unsigned long long timeout = get_time() + 2500000;
    // Accurate to the microsecond.
    // 2.5 s == 2 500 000 us

    while(get_time() < timeout) {
        printf("Hello World\n");
    }

    return 0;
}

Windows:

#include <stdio.h>
#include <windows.h>

unsigned long long get_time(void) {
    SYSTEMTIME time;
    GetSystemTime(&time);

    return time.wSecond * 1000 + time.wMilliseconds;
}

int main(int argc, char* argv[]) {
    unsigned long long timeout = get_time() + 2500;
    // Accurate to the millisecond.
    // 2.5 s == 2 500 ms

    while(get_time() < timeout) {
        printf("Hello World\n");
    }

    return 0;
}

注意,在 Windows 上,精度低至毫秒,而在 Linux 上,精度低至微秒。

关于c - 如何使用 float 来设置超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56199740/

相关文章:

c - 查找所有字符串中存在的共同字符

c - c字符串构造

c - 如何计算这个阶乘

甲骨文10gr2 : enforce dates entered are between 9am and 5pm?

mysql - 时区 America/Los_Angeles 和 US/Pacific 和 PST8PDT 之间的区别?

r - 使用 HR :MIN in R 查找时间平均值

c - 哪个更好地将全局/静态变量初始化为零或保持它们未初始化

c - 如何停止通过输入插入值?

c++ - 如何将秒转换为hh :mm:ss.毫秒格式c++?

使用 newaxis 对 for 循环进行 Python 时间优化