linuxlogginggettimegettimeofdayeglibc

eglibc: Getting Uptime in Milliseconds


I want to write a log-output with the same format as the kernel-log:

[   11.947248] fsl-gianfar ffe24000.ethernet eth0: Link is Up

The timestamp should have the same time-reference as the kernel time. This means, when a log-message is emitted at the same time as it is done in the kernel, the timestamps should have the same value.

The clock_gettime has a undefined clock starting-point - thus the timestamp of every program has a different value - even if they were created at the same time:

clock_gettime(CLOCK_REALTIME, &ts);
clock_gettime(CLOCK_MONOTONIC, &ts);

When using gettimeofday you get the time since the Unix-epoch... which does not match by definition.

The function localtime() returns the uptime - but the granularity is in seconds - but I need more...


Update: It seems that clock_gettime(CLOCK_REALTIME, &ts) should do what I want... but eglibc seems to return CLOCK_MONOTONIC instead.


Solution

  • The idea is first to find the offset for your CLOCK_MONOTONIC. Just read the /proc/uptime once for that. Then use the offset and CLOCK_MONOTONIC to print the time for every logged event.