0

我想知道是否有办法在 ac 程序中获取每一个整数秒。我尝试使用“gettimeofday”函数来获取当前时间,然后如果秒的当前小数部分落入一个区域(比如大于 0.9 且小于 0.1),我将当前时间四舍五入为整数。但是,当我运行程序时,偶尔会错过几秒钟。有没有人有更好的解决方案?

谢谢

4

1 回答 1

0

我建议使用警报信号:

#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>

void timer_handler (int signum)
{
  struct timeval tval;
  gettimeofday(&tval, NULL);
  printf("Seconds: %ld\n",tval.tv_sec);
}

int main ()
{
  struct sigaction sa;
  struct itimerval timer;

  memset (&sa, 0, sizeof (sa));
  sa.sa_handler = &timer_handler;
  sigaction (SIGVTALRM, &sa, NULL);

  timer.it_value.tv_sec = 1;
  timer.it_value.tv_usec = 0;
  timer.it_interval.tv_sec = 1;
  timer.it_interval.tv_usec = 0;
  setitimer (ITIMER_VIRTUAL, &timer, NULL);

  while (1);
}

在我的 Mac (OS X 10.11.5) 上,我得到:

./alarm
秒:1468937712
秒:1468937713
秒:1468937714
秒:1468937715
秒:1468937716
秒:1468937717
秒:1468937718
秒:14689377720
秒:14689

编辑

上面的代码使用了虚拟计时器,它只会在线程运行的时候计时(因此依赖于繁忙的循环来引入高负载)。使用实时计时器可以减少负载:

#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <pthread.h>

void timer_handler (int signum)
{
  struct timeval tval;
  printf("Foo");
  gettimeofday(&tval, NULL);
  printf("Seconds: %ld\n",tval.tv_sec);
}

int main ()
{
  struct sigaction sa;
  struct itimerval timer;
  sa.sa_mask=0;
  sa.sa_flags=0;


  memset (&sa, 0, sizeof (sa));
  sa.sa_handler = &timer_handler;
  sigaction (SIGALRM, &sa, NULL);

  timer.it_value.tv_sec = 1;
  timer.it_value.tv_usec = 0;
  timer.it_interval.tv_sec = 1;
  timer.it_interval.tv_usec = 0;
  setitimer (ITIMER_REAL, &timer, NULL);

  while (1){
    pthread_yield_np();
  }
}

这种方法基本上只运行计时器处理程序。因此操作系统不应该太在意负载。但是,请注意,实时保证只能通过操作系统的实时功能(如果有的话)获得。

于 2016-07-19T14:22:56.880 回答