理解时间的计算(jiffies)

Understanding the calculation of the time (jiffies)

我想在内核中休眠一段特定的时间,我使用 time_beforejiffies 来计算我应该休眠的时间,但是我不明白如何计算确实有效。我知道 HZ250jiffies 是一个巨大的动态值。我知道它们是什么以及它们的用途。

我用jiffies + (10 * HZ)计算时间。

static unsigned long j1;

static int __init sys_module_init(void)
{
    j1 = jiffies + (10 * HZ);
    while (time_before(jiffies, j1))
        schedule();
    
    printk("Hello World - %d - %ld\n", HZ, jiffies); // Hello World - 250 - 4296485594 (dynamic)
    return 0;
}

计算是如何进行的,我会睡多少秒?我想知道,因为以后我可能会想睡一个特定的时间。

HZ 表示一秒内的刻度数,将其乘以 10 得到 10 秒内的刻度数。因此,计算 jiffies + 10 * HZ 得出 jiffies 10 秒后的预期值

但是,不推荐在循环中调用 schedule() 直到达到该值。如果你想在内核中休眠,你不需要重新发明轮子,已经有一套 API 就是为了这个目的,documented here, which will make your life a lot easier. The simplest way to sleep in your specific case would be to use msleep(),传递你想休眠的毫秒数:

#include <linux/delay.h>

static int __init sys_module_init(void)
{
    msleep(10 * 1000);
    return 0;
}