如何让我的程序在每个给定时间(例如 1/s)只迭代一次?

How do I make my program iterate only once every given time (ex 1/s)?

假设我有一个 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. */
    }
  }