Time and date syscalls

clock_gettime

Syscall 228 (clock_gettime) fills a struct timespec with seconds and nanoseconds. Pass the clock ID in RDI (0 for realtime) and a pointer to the struct in RSI:

%define SYS_CLOCK_GETTIME 228 section .bss ts resq 2 ; timespec: sec, nsec section .text mov rax, SYS_CLOCK_GETTIME mov rdi, 0 mov rsi, ts syscall

The timespec struct

The timespec is two 64-bit fields: seconds, then nanoseconds. Read them as two quadwords, and remember the nanosecond field wraps at one billion, so subtracting times needs a borrow check:

mov rax, [ts] ; seconds mov rdx, [ts+8] ; nanoseconds

Measuring elapsed time

Take two readings and subtract. If the end nanoseconds are smaller than the start, borrow one second: add 1,000,000,000 to the end nanoseconds and subtract one from the seconds.

The code on this page was assembled with NASM 3.01 and linked with GNU ld 2.45.1, and the program was run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev