This shows you the differences between two versions of the page.
c:time.h:clock [2013/01/22 22:02] |
c:time.h:clock [2024/02/16 01:04] (current) |
||
---|---|---|---|
Line 1: | Line 1: | ||
+ | {{keywords>wiki library source code example reference}} | ||
+ | ===== clock ===== | ||
+ | |||
+ | <code c> | ||
+ | clock_t clock(void); | ||
+ | </code> | ||
+ | |||
+ | |||
+ | === Description === | ||
+ | |||
+ | The clock() function returns the processor time since the program started, or -1 if that information is unavailable.\\ | ||
+ | To convert the return value to seconds, divide it by CLOCKS_PER_SEC. (Note: if your compiler is POSIX compliant, then CLOCKS_PER_SEC is always defined as 1000000.) | ||
+ | |||
+ | |||
+ | ===== clock c example ===== | ||
+ | <code c> | ||
+ | /* | ||
+ | * clock example code | ||
+ | * http://code-reference.com/c/time.h/clock | ||
+ | */ | ||
+ | #include <stdio.h> | ||
+ | #include <time.h> | ||
+ | |||
+ | int main (void) | ||
+ | { | ||
+ | int sec = 5; | ||
+ | clock_t end = clock() + sec * CLOCKS_PER_SEC; | ||
+ | |||
+ | while (clock() < end) | ||
+ | { | ||
+ | // do something | ||
+ | } | ||
+ | |||
+ | return 0; | ||
+ | } | ||
+ | |||
+ | </code> | ||
+ | |||
+ | or | ||
+ | |||
+ | <code c> | ||
+ | /* | ||
+ | * clock example code | ||
+ | * http://code-reference.com/c/time.h/clock | ||
+ | */ | ||
+ | #include <stdio.h> | ||
+ | #include <time.h> | ||
+ | int main( void ) | ||
+ | { | ||
+ | clock_t start = clock(); | ||
+ | clock_t finish; | ||
+ | int i; | ||
+ | |||
+ | for (i = 0; i < 9999; ++i) { | ||
+ | printf("%i\n", i); | ||
+ | } | ||
+ | |||
+ | finish = clock(); | ||
+ | |||
+ | printf("executed \"printf\" %i times\nCocks per Sec: %li\nStart: %li\nFinish: %li\n",i , CLOCKS_PER_SEC, start, finish); | ||
+ | return 0; | ||
+ | } | ||
+ | |||
+ | </code> | ||
+ | |||
+ | === output === | ||
+ | executed "printf" 9999 times | ||
+ | Cocks per Sec: 1000000 | ||
+ | Start: 0 | ||
+ | Finish: 20000 | ||
+ | |||
+ | |||
+ | ==== see also ==== | ||
+ | [[c:time.h:time|time()]] [[c:time.h:difftime|difftime()]] | ||
+ | |||