-2

I found this code here. If I divide (t2-t1)/CLOCK_PER_SECwill i get time in seconds? How to I find CLOCK_PER_SEC? Is there any better way to find the execution time of a code or a function?

#include<time.h> 
main()
{
    clock_t t1=clock();
    // Your code that takes more than 1 sec; 
    clock_t t2=clock();
    printf("The time taken is.. %g ", (t2-t1));
    ..
Community
  • 1
  • 1
  • Can you say why downvote my question? –  Feb 28 '16 at 14:27
  • 1
    It is `CLOCKS_PER_SEC` not `CLOCK_PER_SEC` and it can be found in `time.h`. Please see the [link in your link](http://stackoverflow.com/questions/1083142/what-s-the-correct-way-to-use-printf-to-print-a-clock-t) – Weather Vane Feb 28 '16 at 16:58
  • Ok thnx, but I think this code does not find real time http://stackoverflow.com/questions/10455905/clocks-per-sec-not-actually-clocks-per-sec. Gsamaras answered it. –  Feb 28 '16 at 17:19
  • But you did not ask for "real time". Your question was "How to find the execution time of code in C?" In the same way that if I spend 30 minutes on a problem, 2 hours shopping, then 30 minutes finishing the problem, it took me 1 hour, not 3 hours. – Weather Vane Feb 28 '16 at 18:30
  • You cannot find the execution time of C code, because C code is never executed. C code has to be compiled first. And it's that compiled code that is then executed. And the execution time depends on what architecture you have compiled the code for, which compiler you used with which options, and which exact processor derivate in which exact configuration you run the compiled code on. And then your execution time can still vary by several orders of magnitude depending on the execution history (cache and pipeline states). Not to mention interrupts. Basically your question makes no sense at all. – ЯegDwight May 24 '17 at 10:23

1 Answers1

0

You could do it like this:

#include <sys/time.h>
#include <time.h>

typedef struct timeval wallclock_t;

void wallclock_mark(wallclock_t *const tptr)
{
    gettimeofday(tptr, NULL);
}

double wallclock_since(wallclock_t *const tptr)
{
    struct timeval  now;
    gettimeofday(&now, NULL);

    return difftime(now.tv_sec, tptr->tv_sec)
            + ((double)now.tv_usec - (double)tptr->tv_usec) / 1000000.0;
}

int main(void)
{
    wallclock_t  t;
    double  s;

    wallclock_mark(&t);

    /*
     * Do something
    */

    s = wallclock_since(&t);
    printf("That took %.9f seconds wall clock time.\n", s);
    return 0;
}

You can read more in my Time measurements.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 1
    I know @user3577378. BTW, I didn't downvote, I upvoted since it's something that buzzed me in the start too. You can compare these two pieces of code, since I do not really remember to tell you. Hope that helps. – gsamaras Feb 28 '16 at 14:35