How to measure time in nanoseconds with C

1 Answer

0 votes
#include <stdio.h>
#include <time.h>
#include <stdint.h>

int main() {
    // Record start time
    struct timespec start, end;
    clock_gettime(CLOCK_MONOTONIC, &start);

    for (int i = 0; i < 1000; i++);

    // Record end time
    clock_gettime(CLOCK_MONOTONIC, &end);

    // Calculate time difference in nanoseconds
    int64_t time_in_nanoseconds = 
        (int64_t)(end.tv_sec - start.tv_sec) * 1000000000 + 
        (end.tv_nsec - start.tv_nsec);

    printf("%ld [ns]\n", time_in_nanoseconds);

    return 0;
}



/*
run:

751 [ns]

*/

 



answered Mar 14, 2025 by avibootz

Related questions

1 answer 218 views
218 views asked Feb 22, 2022 by avibootz
1 answer 126 views
1 answer 262 views
2 answers 175 views
2 answers 167 views
167 views asked Jun 28, 2024 by avibootz
1 answer 157 views
157 views asked May 29, 2023 by avibootz
1 answer 256 views
...