1、调用内核时钟接口打印当前时间
该内核程序调用了timeval、do_gettimeofday、rtc_time、rtc_time_to_tm四个结构体,都是比较简单的用法。
current_time.c:
#include <linux/module.h>
#include <linux/time.h>
#include <linux/rtc.h>
MODULE_LICENSE("GPL");
struct timeval tv;
struct rtc_time tm;
static int __init currenttime_init(void)
{
int year, mon, day, hour, min, sec;
printk("Start current_time module...\n");
do_gettimeofday(&tv);
rtc_time_to_tm(tv.tv_sec, &tm);
year = tm.tm_year + 1900;
mon = tm.tm_mon + 1;
day = tm.tm_mday;
hour = tm.tm_hour + 8;
min = tm.tm_min;
sec = tm.tm_sec;
printk("Current time: %d-%02d-%02d %02d:%02d:%02d\n", year, mon, day, hour, min, sec);
return 0;
}
static void __exit currenttime_exit(void)
{
printk("Exit current_time module...\n");
}
module_init(currenttime_init);
module_exit(currenttime_exit);
编译运行:
查看运行结果,成功在屏幕上打印出格式化的时间、日期,并正确地加载和卸载。
2、编写timer,在特定时刻打印 hello,world
本节使用了内核定时器,对程序进行时间控制,定时器由结构timer_list表示,定义在头文件<linux/timer.h>中,内核程序中包括了创建、初始化、激活三个步骤。
timer_example.c:
#include <linux/module.h>
#include <linux/timer.h>
MODULE_LICENSE("GPL");
struct timer_list timer; //创建
void print(struct timer_list *timer)
{
printk("hello,world!\n");
}
static int __init timer_init(void)
{
printk("Start timer_example module...\n");
//初始化
timer.expires = jiffies + 10 * HZ; //定义定时器超时的节拍数
timer.function = print; //定时器超时后调用print函数
add_timer(&timer); //激活定时器,将定时器注册到内核中
return 0;
}
static void __exit timer_exit(void)
{
printk("Exit timer_example module...\n");
}
module_init(timer_init);
module_exit(timer_exit);
编译运行:
如图,加载该内核模块10秒后打印 ” hello,world!“,因为定时器执行了定时操作。合理使用定时器,可以使工作在指定时间点上执行,我们只需要执行一些初始化工作,设置一个超时时间,指定超时发生后执行的函数,然后激活定时器就可以了。指定的函数在定时器到期时自动执行。
3、调用内核时钟接口,监控累加计算代码的运行时间
sum_time.c:
#include <linux/module.h>
#include <linux/time.h>
MODULE_LICENSE("GPL");
#define NUM 100000
struct timeval tv;
static long sum(int num)
{
int i;
long total = 0;
for (i = 1; i <= NUM; i++)
total = total + i;
printk("The sum of 1 to %d is: %ld\n", NUM, total);
return total;
}
static int __init sum_init(void)
{
int start;
int start_u;
int end;
int end_u;
long time_cost;
long s;
printk("Start sum_time module...\n");
do_gettimeofday(&tv);
start = (int)tv.tv_sec;
start_u = (int)tv.tv_usec;
printk("The start time is: %d s %d us \n", start, start_u);
s = sum(NUM);
do_gettimeofday(&tv);
end = (int)tv.tv_sec;
end_u = (int)tv.tv_usec;
printk("The end time is: %d s %d us \n", end, end_u);
time_cost = (end - start) * 1000000 + end_u - start_u;
printk("The cost time of sum from 1 to %d is: %ld us \n", NUM, time_cost);
return 0;
}
static void __exit sum_exit(void)
{
printk("Exit sum_time module...\n");
}
module_init(sum_init);
module_exit(sum_exit);
编译运行:
由程序运行结果可以看出,从 1 到 100000 的累加和所花时间是1 us。