Algorithms, Blockchain and Cloud

C Program to Time Command using clock_gettime


In C/C++, we can use the clock_gettime method from time.h to get the Seconds and Nano Seconds. The following C runs the external command and measure the time difference:

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

int main(int argc, char* argv[]) {
    char buf[1024];
    int j = 0;
    for (int i = 1; i < argc; ++ i) {
        size_t l = strlen(argv[i]);
        strcpy(buf + j, argv[i]);
        j += l;
        buf[j ++] = ' ';    
    }
    buf[j] = '\0';
    struct timespec curTime, nowTime;
    clock_gettime(CLOCK_REALTIME, &curTime);
    system(buf);
    clock_gettime(CLOCK_REALTIME, &nowTime);
    long int secs = nowTime.tv_sec - curTime.tv_sec;
    long int nsec = nowTime.tv_nsec - curTime.tv_nsec;
    printf("s = %ld\nns = %ld\n", secs, nsec);
    return 0;
}

Compiled with gcc:

$ gcc run.c -o run

And then, we can measure the time of a program (performance profiler):

$ ./run echo Hello, World!
Hello, World!
s = 0
ns = 1379618

We can convert the time into ns so that we can easily measure the performance of a programing or procedure:

uint64_t get_ns(void) {
    uint64_t curr_time_ns = 0;
    struct timespec curr_time = {0, 0};
    clock_gettime(CLOCK_REALTIME, &curr_time);
    return curr_time.tv_nsec + curr_time.tv_sec * 1.0e9;
}

–EOF (The Ultimate Computing & Technology Blog) —

274 words
Last Post: Teaching Kids Programming - Maximum Number of Words You Can Type
Next Post: Teaching Kids Programming - Find the Difference of Two Almost Same Strings

The Permanent URL is: C Program to Time Command using clock_gettime (AMP Version)

Exit mobile version