15

What is the standard way to get the current time in seconds (since the epoch) in a kernel module?

I have seen techniques involving getting xtime which are very long-winded and involve while-loops and locks. There must be a better way.

[This is not a duplicate. I have looked through previous questions on SO. The answers to many of these either don't specify the function used, or incorrectly refer to time.h which is not allowed in the kernel]

HXCaine
  • 4,228
  • 3
  • 31
  • 36
  • what about http://stackoverflow.com/questions/5077192/how-to-get-current-hour-time-of-day-in-linux-kernel-space – MOHAMED Nov 25 '12 at 15:46

1 Answers1

23

You can use getnstimeofday for that.

/* getnstimeofday - Returns the time of day in a timespec */
void getnstimeofday(struct timespec *ts)

where struct timespec is:

struct timespec {
    time_t  tv_sec;     /* seconds */
    long    tv_nsec;    /* nanoseconds */
};

And yes, you'll need #include <linux/time.h>.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • Dead link. A Google search for "man getnstimeofday" gets a number of hits. – Keith Thompson Feb 06 '14 at 21:22
  • @KeithThompson Changed the link. Thanks for the heads-up! – cnicutar Feb 06 '14 at 21:25
  • @KeithThompson I don't think kernel functions have official manual pages. I did find a few pages for "man getnstimeofday" but I am reluctant to link to them. Feel free to edit if you find something useful. – cnicutar Feb 06 '14 at 22:11
  • I dropped the link. The source link you has before didn't seem particularly useful; I found 3 or so supposed man pages, but I didn't like the way they looked, and all the relevant information is in the answer. Of course feel free to edit as you wish. – Keith Thompson Feb 06 '14 at 22:17
  • @KeithThompson I think dropping the link is sensible actually, thanks. – cnicutar Feb 06 '14 at 22:19
  • For now, kernel developers have deprecated this interface, see https://www.kernel.org/doc/html/latest/core-api/timekeeping.html?highlight=getnstimeofday#c.getnstimeofday – Maria Matejka Feb 16 '22 at 10:06