用法:
(图片源于MOOC 浙江大学 陈越)
注意:每台设备的CLK_TCK不一样
运行秒数等于时钟打点数/机器每秒走过的时间打点数
Problem:
(图片源于MOOC 浙江大学 陈越)
方法1(普通算法):
#include <**iostream**>
#include <**cmath**>
#include <**time.h**>
using namespace std;
#define max 100000
int main()
{
void f(double n);
clock_t start,stop;
start=clock();
for(int i=1;i<=max;i++)f(1.1);
stop=clock();
double duration=(stop-start)*1.0/CLK_TCK/max;
cout<<"跑了"<<duration<<"秒"<<endl;
cout<<"设备每秒的打点数为"<<CLK_TCK<<endl;
}
void f(double n)
{
int i=1,sn=1;
for(i=1;i<=100;i++)
sn+=pow(n,i)/i;
}
运行结果
方法2(秦九韶算法):
#include <iostream>
#include <time.h>
using namespace std;
#define max 100000
int main()
{
double f(int x,double a[]);
clock_t start,stop;
double a[101];
for(double i=0;i<101;i++)a[(int)i]=1/i;
start=clock();
for(int i=1;i<=max;i++)f(1.1,a);
stop=clock();
double duration=(stop-start)*1.0/CLK_TCK/max;
cout<<"跑了"<<duration<<"秒"<<endl;
cout<<"设备每秒的打点数为"<<CLK_TCK<<endl;
return 0;
}
double f(int x,double a[])
{
double sn=1;
for(int i=100;i>=0;i--)
{
sn+=a[i-1]+x*a[i];
}
return sn;
}