time difference is zero sec

岁酱吖の 提交于 2020-01-07 03:15:35

问题


Here i am trying to count to calculate time required to complete merge sort.But the difference between start and end is showing zero secend.I don't know what is the problem.For convenience i am posting only the main function where time is calculated.

#include<stdio.h>
#include<time.h>
int main(){
    clock_t start,end,diff;
    start=clock();
    int arr[4]={12,2,56,1};
    int i;
    printf("beforn sort\n");
    printf("\n-------------\n");
    for(i=0;i<4;i++){
        printf("%d ",arr[i]);
    }
    printf("\n \n");
    Merge_sort(arr,0,3);
    printf("after merge sort\n");
    printf("\n-------------\n");
    for(i=0;i<4;i++){
        printf("%d ",arr[i]);
    }
    printf("\n");
    end=clock();
    diff=(double)(end-start)/CLOCKS_PER_SEC;
    printf("total time is %f sec ",diff);
}

回答1:


clock() returns the number of clock ticks elapsed since the program was launched. So that

start=clock();

gives number of clock ticks from program launched till clock() is called. Which gives you clock ticks before sorting.This is number of clock ticks, not seconds.

After sort

end=clock()

gives number of clock ticks from program launched till clock() is called. Which gives you clock ticks after sorting.This is number of clock ticks, not seconds.

Now end-start gives number of clock ticks during sorting process.(This also is not in seconds)

(Number of clock ticks)/(Number of clock ticks in one second)= time in seconds

(end-start)/CLOCKS_PER_SEC gives time required for the sorting process in seconds. But in C this gives an integer. So it has to typecasted to double for precision. That gives.

double diff;
diff=(double)(end-start)/CLOCKS_PER_SEC;



回答2:


CLOCKS_PER_SEC is defined to be type clock_t, which is defined to be an arithmetic type, in N1256 7.23.1. It suggests that clock_t may be an integer type.

I suppose you should change the type of diff to double. Doing so will also make the last usage of printf() correct.



来源:https://stackoverflow.com/questions/36852896/time-difference-is-zero-sec

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