How to get accurate ticks from a timer (high‑resolution timer) in C

1 Answer

0 votes
// Linux / Unix: Use clock_gettime() with CLOCK_MONOTONIC_RAW

#include <stdio.h>
#include <time.h>

long long get_ticks_ns() {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
    
    return (long long)ts.tv_sec * 1000000000LL + ts.tv_nsec;
}

int main() {
    long long start = get_ticks_ns();

    // Do some work
    for (volatile int i = 0; i < 1000000; i++);

    long long end = get_ticks_ns();

    long long elapsed_ns = end - start;
    double elapsed_us = elapsed_ns / 1000.0;
    double elapsed_ms = elapsed_ns / 1000000.0;
    double elapsed_s  = elapsed_ns / 1000000000.0;

    printf("Elapsed ticks (ns): %lld\n", elapsed_ns);
    printf("Elapsed microseconds: %.3f\n", elapsed_us);
    printf("Elapsed milliseconds: %.3f\n", elapsed_ms);
    printf("Elapsed seconds: %.9f\n", elapsed_s);

    // Frequency = ticks per second
    long long frequency = 1000000000LL;
    printf("Timer frequency: %lld Hz\n", frequency);

    return 0;
}



/*
run:

Elapsed ticks (ns): 522641
Elapsed microseconds: 522.641
Elapsed milliseconds: 0.523
Elapsed seconds: 0.000522641
Timer frequency: 1000000000 Hz

*/

 



answered May 9 by avibootz
...