questions on clock(),time() and difftime() in time.h?

廉价感情. 提交于 2019-12-12 01:26:50

问题


int fib(int n,int a,int b){
    if (n==2){
        return a+b;
    }
    return fib(n-1,b,a+b);

}

int main() {
    time_t begin,end;
    begin = clock();
    fib(10000,0,1);
    end = clock();
    printf("%f",difftime(end,begin));
}




int main() {
    time_t begin,end;
    time(&begin);
    fib(10000,0,1);
    time(&end);
    printf("%f",(double)(end-begin)/CLOCKS_PER_SEC);
}

1)First question Why does my first main give prints me a time 288.000000,I'm assuming this is 288 milliseconds but in the documentation it is supposed to give me the result in seconds.I am on Mac by the way.

2)Second Question Why does the second main. Why does this print me the output time being 0.000000. I understand that time() give me a time_t structure that i put inside begin and end time_t structs and then i find the difference in seconds,doesn't seem to work.


回答1:


Yes i am trying to get the difference in seconds between two difference times.

You could try something like the following approach:

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


void timeCheck(int *clock,int *minutes){
    int hour ;
    int minute ;
    time_t end, start;
    double diff;
    size_t seconds;


    start = (time_t)((clock[0] * 60 + clock[1]) * 60) ;
    end = (time_t)((minutes[0] * 60 + minutes[1]) * 60) ;

    if( end < start ){
        end += 24 * 60 * 60 ;
    }

    diff = difftime(end, start);

    hour = (int) diff / 3600;
    minute = (int) diff % 3600 / 60;
    printf("The difference is %d:%d\n", hour, minute);
    seconds = (size_t)(hour * 3600) + (size_t)(minute * 60);
    printf("Seconds = %zu\n",seconds);
}

int main(void) {
    int hour[] = {22,20};
    int minutes[] = {5,40};

    printf("Start time %d:%d\n",hour[0],hour[1]);
    printf("End time %d:%d\n\n",minutes[0],minutes[1]);

    timeCheck(hour,minutes);
    return 0;
}

Output:

Start time 22:20
End time 5:40
The difference is 7:20
Seconds = 26400



回答2:


The return type from clock() is clock_t - not necessarily seconds. Apple : clock. Which measures the number of ticks the CPU has used (CLOCKS_PER_SEC). This value is not necessarily milliseconds or seconds.

time() returns the number of whole seconds since a particular point in time (1/1/1970).

So calling time twice in quick succession, results in the same number of whole seconds.

difftime expects time_t (return type from time()) as its parameters and creates an elapsed time (in seconds).

Thus it is not correct to call for clock_t values.



来源:https://stackoverflow.com/questions/33582874/questions-on-clock-time-and-difftime-in-time-h

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!