C ++ obtain the running time of a process

Source: Internet
Author: User

Use the functions in the C Runtime Library, so it has platform portability.

Include header file: Time. h

# Include <time. h>

Function introduction:

1. Clock ()

Function:

Returns the time taken by the processor to call a process or function.

Function prototype:

Clock_t clock (void );

Return Value:

If the process is successful, the number of CPU tick messages returned from the execution of the process to the time when clock () is called (clock_t is a long integer) is returned)

-1 is returned if the request fails;

Note: To convert clock_t to seconds or milliseconds, divide it by clocks_per_secclk_tck or clk_tck (name earlier than 6.0)

In the time. h file, a constant clocks_per_sec is also defined to indicate the number of clock time units in a second. Its definition is as follows:

# Define clocks_per_sec (clock_t) 1000)

2. difftime ()

Function:

Returns the time interval between two time_t variables, that is, the time difference between two time points.

Function prototype:

Double difftime (time_t Timer1, Time_t
Timer0 );

Parameters:

Timer1: End Time
Timer0: Start Time

Return Value:

Double-precision floating point value

Note: Both clock_t and time_t are unsigned long values, but one represents milliseconds and the other represents seconds.

Example:

# Include <time. h> # include <stdio. h> # include <stdlib. h> void main () {time_t c_start, t_start, c_end, t_end; c_start = clock (); t_start = Time (null ); // used to pause system ("pause"); c_end = clock (); t_end = Time (null); printf ("the pause used % f ms by time (). \ n ", difftime (c_end, c_start); printf (" the pause used % f s by clock (). \ n ", difftime (t_end, t_start ));}

Output result:
The pause used 12203.000000 MS by time ().
The pause used 13.000000 s by clock ().

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.