image University of Washington Computer Science & Engineering
  CSE P527Wi '18:  The Course FAQ
  CSE Home   About Us    Search    Contact Info 

Common questions:

Q.  How do I time my program?

You've asked us to measure the time taken by our algorithms. How do I to this? Should I buy that $3.99 Rolex I keep getting emails about? --- T. Treasure

A.   Dear Timeless,
No, save the Rolex to impress that Certain Someone. Computers generally have built-in clocks. Accesssing them depends on the language. For example, in C/C++, you do:

      #include <time.h>
      int main(void) {
        clock_t start_tick, end_tick;
        double elapsed;

        start_tick = clock();
        my_really_fast_algorithm(42);
        end_tick = clock();
        elapsed = (end_tick - start_tick) / (double)CLOCKS_PER_SEC;
        printf("My Really Fast Algorithm took %f seconds!\n", elapsed);
        return 0;
      }
CLOCKS_PER_SEC, defined in time.h, tells how to scale the system-dependent clock() results to seconds. (It is often 1000, but that does not tell you the resolution of the timer, which is often 10 or .001 milliseconds. Oldtimers remember 16.7 millisecond clocks, i.e., 60 hertz powerline frequency...)

Similarly, in Java public static long currentTimeMillis() returns the current time in millisecond units (but not necessarily millisecond accuracy).

Specific systems may have additional features. These will be less portable, but may be more convenient. E.g., a former student pointed out these "high performance timer" functions for Windows:

If you have a pointer to other useful faclities in these or other languages, please send them to me or post to Catalyst GoPost.


CSE logo Computer Science & Engineering
University of Washington
Box 352350
Seattle, WA  98195-2350
(206) 543-1695 voice, (206) 543-2969 FAX