简体   繁体   中英

c++ implementing clock to measure execution time

I have written a program in c++ and am trying to measure the time it takes to execute completely

int main (int argc, char**argv){
    clock_t tStart = clock();
    //doing my program's work here
    printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
    return 0;
}

My issue is that it will always print out 0.00s for the execution time. Could this be due to using multiple pthreads in my program (my program uses pthread_join to make sure that all threads have completed executing so I don't think this should be an issue)?

edit: //doing program's work =...

for(i = 0;i<4;i++){
    err = pthread_create(&threads[i], NULL, print, NULL); 
    pthread_join(threads[i], NULL);
}

void *print(void *data){
    printf("hello world");
}
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);

All three of your arithmetic operands are integers, so you perform integer division and get 0 .

Cast either the LHS or the RHS of the / symbol to a floating-point type. And run your code more times! Your benchmark is useless if it measures just a single run (which is pretty evident since you got 0 , not 1 or like 300 or something).

It really depends on what is in //doing my program's work here . If it is kicking off other threads, then you will definitely need to wait or poll to get a time. Show the code to get more help! In a similar situation I was in recently, however, it turned out that my code was actually running in less than 0.01 seconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM