Skip to content
shellhacks.dev
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
Summarize in AI

A command seems to hang or run slowly, and you want to know which system call the time goes to.

Shell
strace -T -e trace=clock_nanosleep sleep 0.2 2>&1 | head -n 1
strace -T -e trace=write dd if=/dev/zero of=out bs=50M count=1 2>&1 | grep -E '^write\(1,' | grep -oE '= [0-9]+ <[0-9.]+>'
Text
clock_nanosleep(CLOCK_REALTIME, 0, {tv_sec=0, tv_nsec=200000000}, 0xffffc1e5a988) = 0 <0.200338>
= 52428800 <0.190752>

-T appends the time spent in each traced call, in seconds, in angle brackets at the end of the line. The sleep call shows the 0.2 seconds it was asked for, plus a little overhead. The write shows how long the kernel needed to copy 50 MB, which is where the time of a copy command goes when the disk or the page cache is slow. Pair it with -e trace= to keep only the calls of interest. See the strace manual.

The figure is wall-clock time inside the call, including time spent blocked or descheduled, and it is not CPU time. The tracing overhead makes short calls look longer than they are. Use -c for totals and -r for the gap between calls. Without -f the children of a command are not traced.

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

Count process spawns in a script

Count how many processes a shell script starts with strace -f -c -e trace=execve,clone. A loop that calls date five times runs six execs, and a builtin runs one.

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.