C语言 睡眠时的信号处理速度比旋转慢?



我试图理解为什么当主进程旋转(while(1((时信号处理速度比睡眠更快。

我使用以下代码创建 500us 的一次性计时器 (基于如何在 Linux 用户空间中实现高精度计时器?:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
#define NSEC_PER_SEC 1000000000L
#define timerdiff(a,b) (((a)->tv_sec - (b)->tv_sec) * NSEC_PER_SEC + 
(((a)->tv_nsec - (b)->tv_nsec)))
struct timespec prev;
void handler( int signo )
{
struct timespec now;
unsigned long diff;
clock_gettime(CLOCK_MONOTONIC, &now);
diff = timerdiff(&now, &prev);
printf("%lun", diff);
exit(0);
}
int main(int argc, char *argv[])
{
int i = 0;
timer_t t_id;
struct itimerspec tim_spec = {.it_interval= {.tv_sec=0,.tv_nsec=0},
.it_value = {.tv_sec=0,.tv_nsec=500000}};
struct sigaction act;
sigset_t set;
sigemptyset( &set );
sigaddset( &set, SIGALRM );
act.sa_flags = 0;
act.sa_mask = set;
act.sa_handler = &handler;
sigaction( SIGALRM, &act, NULL );
if (timer_create(CLOCK_MONOTONIC, NULL, &t_id))
perror("timer_create");
clock_gettime(CLOCK_MONOTONIC, &prev);
if (timer_settime(t_id, 0, &tim_spec, NULL))
perror("timer_settime");
#ifdef SLEEP
while(1)
sleep(1);
#else
while(1);
#endif
return 0;
}

如果代码是在定义 SLEEP 的情况下执行的,则 10 次执行会给我:

596940
549098
535758
606020
556990
528634
592051
545047
531079
541067
552520

如果未定义 SLEEP,代码将旋转,我得到这些时间:

512641
510337
509778
510406
510057
507193
511245
511245
511384
509638
510127

那真的更好。

有人可以解释我吗?从睡眠中醒来比中断旋转循环还慢?

它在 Linux 4.9 上尝试了此代码PREEMPT_RT在英特尔平台(8 核(上修补了内核,系统处于空闲状态。

谢谢!

奥雷利安

旋转时,内核不需要准备要运行的进程,因为当信号到达时进程已经在运行。它只需要更改指令指针即可进入信号处理程序。

如果进程处于休眠状态,则必须将其放入任务队列,必须恢复上下文(寄存器,内存映射(以及许多其他准备步骤,直到进程真正运行。

这会产生很小的差异,但如果您查看总数,则总共只有大约 10 - 100 μs。

最新更新