MOOC 1.1 What is a data structure

例1: printN

#include <cstdio> //void PrintN(int N) //{ // for(int i = 1; i <= N; ++ i) // { // printf("%d\n", i); // } // // return ; //} void PrintN(int N) { if(N) { PrintN(N - 1); printf("%d\n", N); } return ; } int main() { int n; scanf("%d", &n); PrintN(n); return 0; }

  

Example Two: polynomial

Running time is less than a tick, that shows how to time a tick used it? (Ie how to measure less than one tick of the program run time?)

Let the function test is repeated a plurality of times to run, so that the measured total hit count clock interval is sufficiently long, the last measured time function of the average calculated for each run to

F // (X) = A0 + ... + AN-A1X + Ix + ANx ^ ^. 1-n-n- 

#include <cstdio> 
#include <the ctime> 
#include <the cmath> 
#define MAXN 10 // maximum polynomial term coefficients, i.e., the order of the polynomial + 1'd 
#define maxk 1E7 // test function of the maximum number of repeated call 

Double F1 (n-int, Double A [], Double X); 
Double F2 (n-int, Double A [], Double X) ; 
void time (double (* f2) (int n, double a [ ], Double X)); 

Double a [MAXN]; // stored polynomial coefficients 

void time (double (* f2) (int n, double a [ ], Double X)) 
{ 
	of clock_t Start, STOP; 
	Double DURATION; 
	Start = clock (); 
	/ * function is called repeatedly play clock to obtain a sufficient number of points * / 
	for (int I = 0; I <maxk; I ++) 
	{ 
		F2 (MAXN -. 1, a, 1.1); 
	} 
	STOP = Clock (); 
	// calculate a function of time from a single run
	duration = ((double)(stop - start)) / CLK_TCK / MAXK;
	printf("ticks = %f\n", (double)(stop - start));
	printf("duration = %6.2e\n", duration);
}

double f1(int n, double a[], double x)
{
	double p = a[0];
	for(int i = 1; i <= n; ++ i)
	{
		p += (a[i] * pow(x, i));
	}
	return p;
}

double f2(int n, double a[], double x)
{
	double p = a[n];
	for(int i = n; i > 0; -- i)
	{
		p = a[i - 1] + x * p;
	}
	return p;
}

int main()
{
	for(int i = 0; i < MAXN; ++ i)
	{
		a[i] = (double)i;
	} 
	
	time(f2);
	
	return 0;
}

/*
ticks = 1813.000000
duration = 1.81e-007

ticks = 297.000000
duration = 2.97e-008
*/

  

Guess you like

Origin www.cnblogs.com/mjn1/p/11419658.html