gpt4 book ai didi

c - 如何让我的程序每次只迭代一次(例如 1/s)?

转载 作者:行者123 更新时间:2023-12-04 10:01:08 25 4
gpt4 key购买 nike

假设例如我有一个 for 循环,它从 .txt 文件中逐行读取指令,我希望做的是让程序每秒执行一次这些指令。我怎么可能做到这一点?

这是我的循环代码:

  for(j = 0; j < PC; j++) {             
txtfilepointer = fopen(listWithTxtFilesToRead[j].name, "r");

while (fscanf(txtfilepointer, "%c %s", &field1, field2) != EOF ) {

// here it should be executing the given instruction every second or so...

printf("whatever the instruction told me to do");
}
}

请忽略变量名称,这只是为了举例。

最佳答案

make the program execute those instructions once every second or so



让它等到所需的时间过去。

假设您想让程序等待一秒或更多秒(并且您在 POSIX 系统上,例如 Linux,它带有 sleep() ),您可以这样做:
#include <time.h> /* for time() */
#include <unistd.h> /* for sleep() */

#define SECONDS_TO_WAIT (3)

...

{
time_t t = time(NULL);

/* Instructions to execute go here. */

while ((time(NULL) - t) < SECONDS_TO_WAIT)
{
sleep(1); /* Sleep (wait) for one second. */
}
}

关于c - 如何让我的程序每次只迭代一次(例如 1/s)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61814045/

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