编写一个求最大值的普通函数mymax1与一个内联函数mymax2分别执行10的9次方,输出两函数花费时间 跪求改错
#include<iostream>
#include<time.h>
using namespace std;
int MyMax1(int m,int n)
{return(m>n)?m:n;}
inline int MyMax2(int m,int n)
{return(m>n)?m:n;
const int NUM=1000;
}
int main()
{int m,n,i,j,k,l;
clock_t start,finish;
double totaltime;
cout<<"输入两个数:";
cin>>m>>n;
start=clock();
for(i=0;i<=NUM;i++)
for(j=0;j<=NUM;j++)
for(k=0;k<=NUM;k++)
l=MyMax1(m,n);
finish=clock();
totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
cout<<1;
cout<<"1运行时间"<<totaltime<<"秒!"<<endl;
l=MyMax2(m,n);
finish=clock();
totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
cout<<2;
cout<<"2运行时间"<<totaltime<<"秒!"<<endl;
}
[解决办法]
#include<iostream>
#include<time.h>
using namespace std;
int MyMax1(int m,int n)
{return(m>n)?m:n;}
inline int MyMax2(int m,int n)
{return(m>n)?m:n;
}
const int NUM=1000;
int main()
{int m,n,i,j,k,l;
clock_t start,finish;
double totaltime;
cout<<"输入两个数:";
cin>>m>>n;
start=clock();
for(i=0;i<=NUM;i++)
for(j=0;j<=NUM;j++)
for(k=0;k<=NUM;k++)
l=MyMax1(m,n);
finish=clock();
totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
cout<<1;
cout<<"1运行时间"<<totaltime<<"秒!"<<endl;
start=clock();
for(i=0;i<=NUM;i++)
for(j=0;j<=NUM;j++)
for(k=0;k<=NUM;k++)
l=MyMax2(m,n);
finish=clock();
totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
cout<<2;
cout<<"2运行时间"<<totaltime<<"秒!"<<endl;
}
[解决办法]
for 循环被完全优化没了,所以两个 clock 调用之间没有任何其他语句,测试的时间自然不正确。
[解决办法]
为了避免优化把
l=MyMax1(m,n);
修改为
l=MyMax1(m+i+j+k,n+i+j+k);
这样再试试