唠嗑
如何判断哪个代码跑得更快呢?可以让电脑来帮我判断。
我用的是#include <time.h>来使用clock()这个函数
电脑每秒钟会打点CLK_TCK(这是个数)次,用了clock(),就知道当时是电脑第几次打点,开始用一次clock结束用一次clock,相减就是这段时间内的打点次数。
上代码
#include <iostream>
#include <time.h>
clock_t a, z;
double dur;
using namespace std;
void printN(int n)
{
int i = 1;
while (i <= n) { cout << i++ << endl; }
}
void printn(int n)
{
int i = 1;
for (; i <= n; i++)cout << i << endl;
}
void main()
{
int n;
cin >> n;
a= clock();
printN(n);
z = clock();
dur = (double)(z-a) / CLK_TCK;
cout << dur;
a = clock();
printn(n);
z = clock();
dur = (double)(z - a) / CLK_TCK;
cout << dur;
}
当函数作为参数
#include <iostream>
#include <time.h>
#include <math.h>
clock_t a, z;
double dur;
using namespace std;
void fun1(double x)
{
int i = 100;
double sum=0;
for (; i; i--)
{
sum *= x;
sum += (x / i);
}
cout<< sum + 1<<endl;
}
void fun2(double x)
{
int i = 1;
double sum = 1;
for (; i<=100; i++)
{
sum += pow(x,i)/i;
}
cout<<sum<<endl;
}
void tim(double x,void (* fun)(double))
{
a = clock();
fun(x);
z = clock();
dur = (double)(z - a) / CLK_TCK;
cout << dur<<endl;
}
void main()
{
double x;
cin >> x;
tim(x, fun1);
tim(x, fun2);
}
运行界面
1
6.18738
0.002
6.18738
0.001
|