How to measure processor time and wall time?

I have seen many topics about this, even in stackoverflow, for example:

How to measure CPU time and wall time on Linux / Windows?

I want to measure both the processor and the wall time. Although the person who answered the question in the topic that I posted, we recommend using it gettimeofdayto measure time on the wall, I read that it is better to use instead clock_gettime. So, I wrote the code below (is it normal, does it really measure the wall time, not the processor time? I ask because I found the web page: http://nadeausoftware.com/articles/2012/03/c_c_tip_how_measure_cpu_time_benchmarking#clockgettme , which says that it clock_gettimemeasures the time of the processor ...) What is the truth and which one should be used to measure the time on the wall?

Another question about processor time. I found the answer, which is clockgreat about this, so I wrote a sample code for it. But this is not what I really want, for my code it shows me 0 seconds of processor time. Is it possible to more accurately measure the processor time (in seconds)? Thanks for any help (at the moment I am only interested in Linux-solutions).

Here is my code:

#include <time.h>
#include <stdio.h>      /* printf */
#include <math.h>       /* sqrt */
#include <stdlib.h>

int main()
{
    int i;
    double sum;

    // measure elapsed wall time
    struct timespec now, tmstart;
    clock_gettime(CLOCK_REALTIME, &tmstart);
    for(i=0; i<1024; i++){
        sum += log((double)i);
    }
    clock_gettime(CLOCK_REALTIME, &now);
    double seconds = (double)((now.tv_sec+now.tv_nsec*1e-9) - (double)(tmstart.tv_sec+tmstart.tv_nsec*1e-9));
    printf("wall time %fs\n", seconds);

    // measure cpu time
    double start = (double)clock() /(double) CLOCKS_PER_SEC;
    for(i=0; i<1024; i++){
        sum += log((double)i);
    }
    double end = (double)clock() / (double) CLOCKS_PER_SEC;
    printf("cpu time %fs\n", end - start);

    return 0;
}

Compile it as follows:

gcc test.c -o test -lrt -lm

and he shows me:

wall time 0.000424s
cpu time 0.000000s

I know I can do more iterations, but that is not the point.)

IMPORTANT:

printf("CLOCKS_PER_SEC is %ld\n", CLOCKS_PER_SEC);

shows

CLOCKS_PER_SEC is 1000000
+3
source share
1 answer

According to my manual page clockit says

POSIX requires CLOCKS_PER_SEC to be 1,000,000 regardless of the actual resolution.

100000 . , 10 .

, , sum . , clock , .

- . - , , clock, . , C, clock . , clock , , volatile. . , , . , clock , . .

, -, , , , .

- , - . . , Pentium, , , .

, , pragma, , . . , , .

+5

Source: https://habr.com/ru/post/1691355/


All Articles