Clock (): The time it takes to capture a call from the beginning of the program to the clock (). This unit of time is clock tick, which is called "clocking".
Constant CLK_TCK: The number of clock ticks per second that the machine clock has taken.
1#include <stdio.h>2#include <time.h>3 4 colck_t start, stop;5 /*clock_t is the variable type returned by the clock () function*/6 7 Doubleduration;8 /*record the elapsed time of the measured function in seconds*/9 Ten intMain () One { A /*preparations not in the test range are written before the clock () call*/ -start = Clock ();/*Start Timing*/ -MyFunction ();/*add the measured function here .*/ thestop = Clock ();/*Stop Timing*/ -Duration = ((Double) (Stop-start))/Clk_tck; - - /*other processes not in the test range are written in the following, eg: the value of the output duration*/ +}
Experiment _eg: Perform the following print once "Hello world! "The Time
Note: Because the program executes too fast, it is displayed as 0;
1#include <stdio.h>2#include <time.h>3 voidhello ();4 intMain () {5 clock_t start, stop;6 Doubleduration;7Start =clock ();8 hello ();9Stop =clock ();TenDuration = ((Double) (Stop-start))/Clk_tck; Oneprintf"The program run time is:%f\n", duration); A return 0; - } - voidHello () { theprintf"Hello world!\n"); -}
Solution: Let the measured function repeat the full number of times, so that the measured total clock interval is sufficiently long, and finally calculate the average running time of the measured function.
1#include <stdio.h>2#include <time.h>3 4 #defineMAXK 1e5/* Maximum number of repeated calls to the measured function */5 6 voidhello ();7 intMain () {8 inti;9 clock_t start, stop;Ten Doubleduration; OneStart =clock (); A for(i=0; i<maxk; i++){ - hello (); - } theStop =clock (); -Duration = ((Double) (Stop-start))/clk_tck/maxk; - -printf"Duration =%f\n", duration);//around 0.00003s + return 0; - } + A voidHello () { atprintf"Hello world!"); -}
C language-use the clock () function to get program execution time