Skip to content
systemcoding.dev
Assembly

Read the TSC in C with asm volatile and =a, =d outputs

Read the x86 time-stamp counter from C with asm volatile and the =a, =d output constraints that map EDX:EAX.

1 min read
Summarize in AI

rdtsc returns the 64-bit time-stamp counter split across two registers, with the high half in EDX and the low half in EAX. GCC's =a and =d output constraints name exactly those registers, so no mov instructions are needed. The wrapper below compiles with GCC 14 for x86-64.

rdtsc.cc
#include <stdint.h>
#include <stdio.h>

static inline uint64_t rdtsc(void)
{
    uint32_t lo, hi;
    __asm__ volatile ("rdtsc" : "=a"(lo), "=d"(hi));
    return ((uint64_t)hi << 32) | lo;
}

int main(void)
{
    uint64_t t0 = rdtsc();
    uint64_t t1 = rdtsc();
    printf("advanced: %d\n", t1 > t0);
    return 0;
}
Text
advanced: 1

volatile is what keeps the two reads apart: the statement has no inputs, so without it GCC may treat both as the same value and merge them. The instruction is not serialising, so the CPU can still execute it before earlier instructions finish, and the counter's tick rate is a fixed reference frequency rather than the core clock on current Intel and AMD parts. Put an lfence before it when you time short sections, as the Intel Software Developer's Manual describes. The compiler also provides __rdtsc() in x86intrin.h.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.