您的位置:首页 > 编程语言 > C语言/C++

C语言学习之时钟函数clock()函数

2017-03-25 10:19 204 查看
// nomial.cpp : Defines the entry point for the console application.

//多项式求解

//计时函数

//clock():从捕捉程序开始运行到clock()函数被调用所耗费的时间,这个时间单位是

//clock tick,即”时钟打点“,常数CLK_TCK:机器时钟每秒所走的时钟打点数

//包含头文件<time.h>

//fx = a+x(b+x(...))

#include "stdafx.h"
#include <stdlib.h>
#include <math.h>//for pow()
#include <time.h>

#define MAXN 10//多项式最大项数
#define MAXK 1e7//被测函数最大重复调用次数,注意指数为一e7,不是小写的L,因为一次计算运行太快,可能不足一个时钟计数单位

clock_t start, stop;//clock_t是clock()函数返回类型
double duration;

//笨方法
double Function1(int n, double a[], double x)
{
int i;
double p = a[0];
for (i = 1; i < n; i++)
p += (a[i] * pow(x, i));//指数次方共相乘i-1次,再乘以a[i],所以共相乘i次,所以乘法的总次数为(1+2+...+n)
return p;
}

double Function2(int n, double a[], double x)
{
int i;
double p = a
;
for (i = n; i > 0; i--)
p = a[i - 1] + x*p;//共做了n次乘法
return p;
}

int main()
{

int i;
double a[MAXN];//存储多项式的系数
for (i = 0; i < MAXN; i++)
a[i] = (double)i;

//可以将以下语句设计成一个函数调用
start = clock();//开始计时
for(i = 0;i < MAXK;i++)
Function1(MAXN-1,a,1.1);
stop = clock();//停止计时
duration = ((double)(stop - start) / CLK_TCK/MAXK);

printf("tick1 = %f\n", (double)(stop - start));
printf("duration1 =  %6.2e\n", duration);

start = clock();//开始计时
for (i = 0; i < MAXK; i++)
Function1(MAXN - 1, a, 1.1);
Function2(MAXN - 1, a, 1.1);
stop = clock();//停止计时
duration = ((double)(stop - start) / CLK_TCK/MAXK);

printf("tick2 = %f\n", (double)(stop - start));
printf("duration2 =  %6.2e\n", duration);

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: