0

I use "time.h" in my program for have the execution time elapsed from a point to another point of code:

    #include <time.h>

    ...

    //clock
    clock_t avvio;
    clock_t fine;

    //start measurement
    avvio = clock();

    .....
    do works
    ....

     //end measurement
    fine = clock()-avvio;

    //conversion in seconds
    double tempoimp = fine / (double)CLOCKS_PER_SEC;

I have found here this code, and use it. Works, but the "elapsed" second it's simply fine / 1000 , and this assumes a "hard real time" system, that my notebook isn't.

So, what do you advise me to use to have the measure of time it takes for a set of instructions, so I can have the execution time in seconds of my program?

I need the real milliseconds ... not a division of clock cycles ...

Someone can help me??

Domenico
  • 292
  • 2
  • 10
  • 26
  • possible duplicate of http://stackoverflow.com/questions/795827/testing-the-performance-of-a-c-app – tay10r Jun 09 '13 at 08:13
  • I have searched before post question...more similar answer..but all with the same library and situation of that I've post. Instead, I ask to advice me what's library or code I have to use for obtain a real time (in second) representation... – Domenico Jun 09 '13 at 13:17

1 Answers1

2

You can use clock_gettime, which provides a higher resolution timer.

struct timespec t1 = { 0, 0 },
                t2 = { 0, 0 };

if (clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &t1) < 0){
    perror ("Failed to get cpu time");
    return -1;
}

/* test code starts here */

for (int i = 0; i < 200000000; i++); // hefty loop

/* test code ends here */

if (clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &t2) < 0){
     perror ("Failed to get cpu time");
     return -1;
}

printf ("Test code took %d.%d\n",
       (int)(t2.tv_sec - t1.tv_sec),
       (int)(t2.tv_nsec - t1.tv_nsec));

But clock cycles will more accurately reflect the execution speed of your code. You can't, as accurately, measure program speed using any measurement of time. This is because there are a lot of variables which may influence the execution time of your program:

  • The number of other processes running
  • The amount of available ram on your computer
  • Changes in the processors clock speed

Update (for Windows):

#include <stdio.h>
#include <windows.h>

int main (){

    LARGE_INTEGER count1, count2, freq;

    if (!QueryPerformanceCount (&count1)){
            perror ("Couldn't get first count");
            return -1;
    }

    for (int i = 0; i < 200000000; i++);

    if (!QueryPerformanceCount (&count2)){
            perror ("Couldn't get second count");
            return -1;
    }

    if(!QueryPerformanceFrequency(&freq)){
        perror ("Couldn't get processor frequency");
        return -1;
    }

    #if ( __WORDSIZE == 64 )
    #pragma message "Performing 64-bit build"

    printf ("The difference is %ll\n", count2.QuadPart - count1.QuadPart);
    printf ("Time (appx): %l\n", (count2.QuadPart - count1.QuadPart) / freq.QuadPart );
    #else 
    #pragma message "Performing 32-bit build"

    /* The code for 32-bit builds here is incomplete. The difference
     * becomes inaccurate after the time has exceeded 32-bits. You can 
     * work out the math to compensate for that, or just start compiling
     * for 64-bit builds. (Google "compile 64 bit visual studio").
     *
     * 
     */

    #endif

    /* A processor frequency can change during a 
     * computationally intensive program. Therefore,
     * the difference in clock ticks (above) is the most
     * accurate way to measure performance.
     */
}
tay10r
  • 4,234
  • 2
  • 24
  • 44
  • I need a precision timer that give me the time elapsed in milliseconds from a point to another point...enviroment is Visual C++ 2010, Windows 7...this code that you've posted is accurate? – Domenico Jun 10 '13 at 16:28
  • 1
    yes, it should be in `time.h`. Are you getting compilation errors? – tay10r Jun 10 '13 at 23:57
  • Yes...don't compile...get error on struct (t1 and t2 not recognized...) Why? – Domenico Jun 11 '13 at 06:22
  • it might not be on windows. I'll update an example using `QueryPerformanceCounter` from `windows.h` – tay10r Jun 11 '13 at 06:40
  • 1
    *updated the example. You may have to work with me a little on this one, because I don't have a windows computer to test this on. – tay10r Jun 11 '13 at 06:49
  • don't work...give me and error on string: LARGE_INTEGER and at output says "aspect string"...paste error messages: error C2440: 'inizializzazione': impossibile convertire da 'int' a 'LARGE_INTEGER' 1> Nessun costruttore ha potuto accettare il tipo di origine o la risoluzione dell'overload del costruttore è risultata ambigua 1>c:\opencv\test\elaboraimmagini\conthread100t.cpp(219): warning C4081: previsto '('. Trovato 'stringa'. 1> – Domenico Jun 11 '13 at 07:04
  • can you be more specific? have you tried using `%ld` instead of `%ll`? Do you have a 32-bit or a 64-bit computer? – tay10r Jun 11 '13 at 07:06
  • error C2440: 'inizializzazione': impossibile convertire da 'int' a 'LARGE_INTEGER' 1> Nessun costruttore ha potuto accettare il tipo di origine o la risoluzione dell'overload del costruttore è risultata ambigua 1>c:\opencv\test\elaboraimmagini\conthread100t.cpp(219): warning C4081: previsto '('. Trovato 'stringa'. The first error it's releated to first assignment LARGE_INTEGER count = 0 and the second it's related to output pragma message... 1> – Domenico Jun 11 '13 at 07:08
  • 1
    take out `= 0` at the declaration, that wasn't suppose to be there. – tay10r Jun 11 '13 at 07:08
  • Removed assignation...Now says "The difference is 0"...after run program...I have modified code in second output (that releated to 32bit) "count2 - count1" and not "count2- count2"...but the number that came out what is? milliseconds? I have to /1000 it? – Domenico Jun 11 '13 at 07:10
  • 1
    because you have a `32-bit` computer and I accidentally wrote `count2.u.LowPart - count2.u.LowPart`. Change that into `count2.u.LowPart - count1.u.LowPart` – tay10r Jun 11 '13 at 07:11
  • I have modified code in second output (that releated to 32bit) "count2 - count1" and not "count2- count2"...but the number that came out what is? milliseconds? I have to /1000 it? – Domenico Jun 11 '13 at 07:13
  • 1
    not quite, you have to query the processor frequency. I'll update my answer in just a moment – tay10r Jun 11 '13 at 07:15
  • Why give me "zero" as time? Says "difference is: 1629064 and Time 0. – Domenico Jun 11 '13 at 07:35
  • it's probably cause the frequency is in the HighPart. can you try compiling into 64 bit mode? or try switching `LowPart` to `HighPart` (as I did in the answer). – tay10r Jun 11 '13 at 07:37
  • But, I use OpenCV 32bit dll, for compile in 64bit I have to change anythings? – Domenico Jun 11 '13 at 07:40
  • yes you would have to change some things up. Try changing `LowPart` to `HighPart` ( I did in the answer ). – tay10r Jun 11 '13 at 07:45
  • Try to change like in your answer and give error "integer division by zero"...if you think that is best, I change all to x64... – Domenico Jun 11 '13 at 08:05
  • I have convert to x64...compile and says "error division by zero"...why??? And you've to correct in the anwer "QueryPerformanceCount" to "QueryPerformanceCounter" that give me an error...and the output function parameter like %ll don't work... – Domenico Jun 11 '13 at 09:17
  • I'm not quite sure why it's doing that. I would suggest using an external program to analyze your performance, like `verysleepy`, found here http://www.codersnotes.com/sleepy/sleepy. I just tested it, seems pretty legit. – tay10r Jun 11 '13 at 20:09