Course contentsShow
← Linux
Lesson 535 of 1,8195. Process Management and SignalingFree lesson

Measuring Process CPU Cycles

Use high-precision counters to track the true CPU consumption of specific code blocks.

In this lesson, you will learn how to use high-precision hardware counters to measure the exact CPU clock cycles consumed by specific sections of your code.

While standard tools like top or /proc/[pid]/stat give you a broad look at process CPU usage, they are often too coarse to measure the performance impact of a specific function or logic block. To capture the true cost of execution, we rely on hardware-level counters that track the CPU’s clock cycles in real-time.

Using the Time Stamp Counter (TSC)

On modern x86 processors, the RDTSC (Read Time-Stamp Counter) instruction provides the most granular measurement possible. It returns the number of clock cycles that have elapsed since the processor was reset. By reading this value immediately before and after a specific code block, you can determine exactly how many cycles your logic required to execute.

Here is a simplified example of how this is implemented in C:

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

static inline uint64_t get_cycles() {
    unsigned int lo, hi;
    __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
    return ((uint64_t)hi << 32) | lo;
}

void measure_task() {
    uint64_t start = get_cycles();
    
    // The specific code block you want to measure
    do_heavy_computation();
    
    uint64_t end = get_cycles();
    printf("Cycles consumed: %lu\n", end - start);
}

Why Precision Matters

Using this method bypasses the delays inherent in system calls and OS scheduling metrics. Because this code runs at the instruction level, it isn't affected by the kernel's scheduler latency or the jitter of interrupt handling. You are effectively capturing the "raw" performance cost of the CPU hardware executing your instructions.

However, keep in mind that these cycle counts represent the time the CPU spent on the task, but they do not account for external factors like cache misses or branch mispredictions that might have occurred during execution. Despite this, it remains the gold standard for micro-benchmarking process behavior.

Key Takeaway: High-precision hardware counters allow you to measure CPU execution cost with near-perfect accuracy, ignoring external OS noise.