How can I clock the speed of a few algorithms I wrote? I wanna see which one's faster.
How can I clock the speed of a few algorithms I wrote? I wanna see which one's faster.
Hmm, not sure, but maybe this...Two things. First, in retrospect, maybe representing the time as a float makes more sense. Second, I think that clock measures how much processor time your application is getting, which isn't neccisarily the same as how much time it actually takes, although if that is so, then it's a better representation of algorithm efficiency.Code:#include <time.h> ... clock_t time1, time2; time1 = clock(); algorithm(); time2 = clock(); printf("Algorithm took %d seconds.\n", (time2 - time1) / CLOCKS_PER_SEC);
Most timer functions are not very acurate as they have about the lowest priority of the windows messages.
Don't depend on them too much, especially if your algorithms are close in speed.
Good question KEN. I don't know the answer either, yet there are obviously people who run these tests on a regular bases, or so they think.
I think I found something. I'll post it later.
Last edited by Troll_King; 10-23-2001 at 02:21 AM.
There is a section in the text 'Algorithms in C++' by Robert Sedgewick. I could type this out if you really want it. Let me know. It is 3 pages long. Infact, now I see that there is a whole chapter dedicated to this. I don't want to type that. Get the book.
ISBN: 0201350883
Last edited by Troll_King; 10-23-2001 at 02:32 AM.
you could probably do it with a couple of calls to QueryPerformanceCounter(). Dig out your msdn cds ken and look it up.
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
The fastest clock going is the time stamp counter on pentium type processors (and I assume compatibles)
It's a short asm sequence which will need to be adapted to your specific compiler.
Here are a couple of examples to work from - the first is GCC, I don't know what the latter one is for.
Code:#include <stdio.h> /* * This macro found on * http://www.c-for-dummies.com/compilers/djgpp_asm.html */ #define RDTSC(llptr) ({ \ __asm__ __volatile__ ( \ ".byte 0x0f; .byte 0x31" \ : "=A" (llptr) \ : : "eax", "edx"); }) int main ( ) { unsigned long long a, b; RDTSC(a); RDTSC(b); printf( "%lld -> %lld = %lld\n", a, b, b-a ); return 0; } #include <stdio.h> unsigned long ReadChipTimer() { unsigned long x; _asm { rdtsc mov x, eax } return x; } int main(void) { unsigned long start, end; start = ReadChipTimer(); end = ReadChipTimer(); printf("Time = %u clock cycles ", end - start); return 0; }
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Thnaks, that ReadChipTimer function helped - the only problem is that it gives a different number each time...as would be expected, but at least the difference between the two speeds is always about equal.