Skip to content
Advertisement

Printing current time in milliseconds or nanoseconds with printf builtin

We can print the current time with the builtin printf function, without needing to invoke an external command like date, like this:

JavaScript

How can we make printf to print milliseconds or nanoseconds as well? Using %3N or %N in the format string doesn’t work:

JavaScript

However, the date command works fine:

JavaScript

This is on a Red Hat Linux version 7.3.

Advertisement

Answer

In bash 5, you can get microsecond precision from EPOCHREALTIME. However, printf itself has no way to access that directly, so you need to extract the microseconds yourself.

JavaScript

This takes a little time, but the result appears to be accurate to about 0.05 milliseconds.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement