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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#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;
}
#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:

1
$ gcc run.c -o run
$ gcc run.c -o run

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

1
2
3
4
$ ./run echo Hello, World!
Hello, World!
s = 0
ns = 1379618
$ ./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:

1
2
3
4
5
6
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;
}
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) —

GD Star Rating
loading...
291 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

Leave a Reply