Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - How to use the clock () function in C language?
How to use the clock () function in C language?
Clock () is a timing function in C/C++, and its related data type is clock _ t.

Its specific function is to return the time taken by the processor to call a process or function. This function returns the number of CPU clock ticks between "starting the program process" and "calling the clock () function in the program", where clock_t is the data type used to save time.

In the time.h file, we can find its definition:

#ifndef _CLOCK_T_DEFINED?

Typedef long clock _ t;; ?

#define _CLOCK_T_DEFINED?

#endif?

Clock_t is actually very long, that is, long shaping. The return value of this function is the number of hardware clock cycles, which needs to be divided by CLK_TCK or CLK_TCK clock cycles/second to be converted into seconds or milliseconds. For example, under VC++6.0, the values of these two quantities are both 1000, which means hardware tick 1000 1 second, so to calculate the time of a process, just divide clock () by 1000.

The reason why the return value of clock is always 0 is:

1, compiler optimization, the for loop was actually not executed at all, and it was skipped directly, so the time was 0.

2.clock calculation program takes up cpu time. If your program performs few actions, then the clock calculation time is also very small.

3. It is suggested to use the time gettimeofday function to time.

Extended data:

C language clock () function program example 1: (running under TC)

# Contains? & ltstdio.h & gt

# Contains? & lttime.h & gt

int? Major (invalid)

{

clock_t? Start,? End;

Start? =? clock();

Delayed (2000);

End? =? clock();

printf("The? Time? Yes: %f\n ",(Double) (End? -? Start)? /? CLK _ TCK);

Return? 0;

}

Description: CLK_TCK? Time. h:# define defined in TC? CLK_TCK 18.2 .

There is also a macro definition of CLK_TCK in VC6.0, but its value is no longer 18.2, but 1000.

Actually, CLK_TCK is completely equivalent to clock _ per second in VC6.0.

Baidu Encyclopedia-Clock ()