Search

Using sched_clock to get kernel uptime

In this post we will see how we can get the information of number of nanoseconds the kernel has been working from and how to print it. We will create a proc entry which when read will print the number of nano seconds from which the kernel has been up for.

The function that is available in kernel to get information about the kernel uptime in nano seconds is sched_clock. sched_clock for x86 is defined as a function in the file "arch/x86/tsc.c", which basically overwrites a default version of the function.

According to the linux documentation : "This function shall return the number of nanoseconds since the system was started. An architecture may or may not provide an implementation of sched_clock() on its own. If a local implementation is not provided, the system jiffy counter will be used as sched_clock()."

To use the function in a module we will need the header file "linux/sched/clock.h"

The function is called with no arguments and returns a "unsigned long long".

In the code below a proc entry is created that will print out the output of sched_clock by converting it to the string.



The details of proc entry and its creation have been discussed in the posts
Creating read only proc entry in linux 5.3

Creating proc read write function in linux kernel 5.3

. The following is the full code for creating the proc entry to display the system up time in nanoseconds



Assuming the above file is saved as "proc_read_time.c". Here is the makefile that can be used to compile the code.



Once the code gets compiled successfully, insert the module using

To test the code , read the proce entry that was created using the cat command

The number shown is the number of nano seconds from which the kernel has been running.


No comments:

Post a Comment