C library function - clock()
Description
C Library Function clock_t clock(void) Returns the processor clock time used since program execution began (usually from the start of the program). To obtain the number of seconds used by the CPU, you need to divide by CLOCKS_PER_SEC.
On 32-bit systems, CLOCKS_PER_SEC equals 1000000, and the function returns the same value approximately every 72 minutes.
Declaration
The following is the declaration of the clock() function.
clock_t clock(void)
Parameters
- NA
Return Value
The function returns the processor clock time used since program start. If it fails, it returns -1.
Example
The following example demonstrates the use of the clock() function.
Example
#include
<
time.h
#include
<
stdio.h
int
main
(
)
{
clock_t
start_t
,
end_t;
double
total_t
;
int
i
;
start_t
=
clock
(
)
;
printf
(
"
Program started, start_t = %ld
\
n
"
,
start_t
)
;
printf
(
"
Starting a large loop, start_t = %ld
\
n
"
,
start_t
)
;
for
(
i
=
0
;
i
<
10000000
;
i
++
)
{
}
end_t
=
clock
(
)
;
printf
(
"
Large loop ended, end_t = %ld
\
n
"
,
end_t
)
;
total_t
=
(
double
)
(
end_t
start_t
)
/
CLOCKS_PER_SEC
;
printf
(
"
Total CPU time: %f
\
n
"
,
total_t
)
;
printf
(
"
Program exiting...
\
n
"
)
;
return
(
0
)
;
}
Let's compile and run the above program, which will produce the following result:
程序启动,start_t = 2614
开始一个大循环,start_t = 2614
大循环结束,end_t = 28021
CPU 占用的总时间:0.025407
程序退出...
C Standard Library -