C language program running time calculation method

Source: Internet
Author: User

1. Sometimes we need to calculate the execution time of the program. For example, if we want to analyze the algorithm time, we can use the following function.

Precise to us.
 
# Include <sys/time. h> int gettimeofday (struct timeval * TV, struct timezone * tz); strut timeval {long TV _sec;/* seconds */long TV _usec;/* microseconds */}; gettimeofday saves the time in the Structure TV. tz Is generally replaced by null. # include <sys/time. h <# include <stdio. h <# include <math. h <void function () {unsigned int I, j; Double Y; for (I = 0; I <1000; I ++) for (j = 0; j <1000; j ++) y = sin (double) I);} Main () {struct timeval tpstart, tpend; float timeuse; gettimeofday (& tpstart, null); function (); gettimeofday (& tpend, null); timeuse = 1000000 * (tpend. TV _sec-tpstart. TV _sec) + tpend. TV _usec-tpstart. TV _usec; timeuse // = 1000000; printf ("used time: % F \ n", timeuse); exit (0 );}

This program outputs the execution time of the function. We can use this to test the system performance or analyze the efficiency of the function algorithm. One output result on my machine is: used time: 0.556070.

2. The second is what I often use:

Before executing the program, add time, for example, input time./ABC, accurate to Ms.

3. clock function (accurate to 1/clocks_per_sec seconds, in milliseconds)

# Include <iostream>
# Include <ctime>
Using namespace STD;
Int max (int x, int y)
{
Return (x> Y )? X: Y;
}
Int main ()
{
Const double begin = clock ();
For (INT I = 10000; I> 0; I --)
For (Int J = 10000; j> 0; j --)
Max (I, j );
Const Double end =

Clock ();

Cout <begin <"" <end;
Return 0;
}

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.