Skip to content
shellhacks.dev
Performance

Time a command with milliseconds

Time a command to the millisecond in Bash 5 with EPOCHREALTIME, which holds the epoch time with microseconds and needs no date or bc process.

1 min read
Summarize in AI

time reports seconds with a fixed format, and you want a number of milliseconds you can compare in a script.

Shell
start=$EPOCHREALTIME
sleep 0.2
end=$EPOCHREALTIME
echo "start=$start"
echo "elapsed: $(( (${end/./} - ${start/./}) / 1000 )) ms"
Text
start=1793973180.212441
elapsed: 200 ms

Bash 5.0 added EPOCHREALTIME, which expands to the seconds since the epoch with a six digit fraction, as listed among the shell variables. Deleting the dot with ${var/./} turns each reading into microseconds, an integer that shell arithmetic can subtract, and dividing by 1000 gives milliseconds. Nothing is forked, so the measurement does not add its own cost.

The exact figure changes on every run, and sleep 0.2 can report a few milliseconds above 200. The locale can change the decimal separator in EPOCHREALTIME, so a comma in the output breaks the substitution. Set LC_NUMERIC=C in that case. It needs Bash 5.0 or later, not the 3.2 that macOS ships.

Share

More snippets

Performance

Count lines in a huge file fast

Count the lines of a big file with wc -l, which is the fastest of the usual tools. It counts newlines, so a last line without a newline is not counted.

2 min read
Performance

Find syscalls that take time

Show how long each system call takes with strace -T. The figure in angle brackets is the time spent inside the call, so a slow write or sleep stands out.

1 min read
Performance

Trace file opens of a command

Find which files a command opens with strace -e trace=openat, and add -e status=failed to see the config files it looked for and did not find.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.