gpt4 book ai didi

c - 如何在c程序中获取每个整数秒

转载 作者:行者123 更新时间:2023-11-30 16:59:04 25 4
gpt4 key购买 nike

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

谢谢

最佳答案

我建议使用警报信号:

#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
Seconds: 1468937712
Seconds: 1468937713
Seconds: 1468937714
Seconds: 1468937715
Seconds: 1468937716
Seconds: 1468937717
Seconds: 1468937718
Seconds: 1468937719
Seconds: 1468937720

编辑

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

#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();
}
}

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

关于c - 如何在c程序中获取每个整数秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38385866/

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