运算与时间(Debug、windowsXP、dell dimension 5150)

来源:互联网 发布:网络三国小说排行 编辑:程序博客网 时间:2024/06/05 05:59
 
  1. #include <afxwin.h>
  2. #include <iostream>
  3. using namespace std;
  4. //一亿次,用了34秒;一千万次,用了2秒;
  5. void main()
  6. {
  7.     CTime t1 = CTime::GetCurrentTime();
  8.     double j =2.345;
  9.     for (int i=0;i<100000000;i++)
  10.     {
  11.         j=j*1.0001234112;
  12.     }
  13.     CTime t2 = CTime::GetCurrentTime();
  14.     CTimeSpan t=t2-t1;
  15.     cout<<t.GetMinutes()<<' '<<t.GetSeconds()<<endl;
  16. }

以上是double类型的乘法运算,比加法慢了10倍吧!

不过,“赋值操作”也相当耗时间,将j=j*1.0001234112;改成j*1.0001234112; 省略赋值运算的话,十亿次运算,用了3秒。

double类型的乘法运算

  1. #include <afxwin.h> 
  2. #include <iostream> 
  3. using namespace std;
  4. //十亿次,用了3秒
  5. void main()
  6. {
  7.     CTime t1 = CTime::GetCurrentTime();
  8.     double j =2.345;
  9.     for (int i=0;i<1000000000;i++)
  10.     {
  11.         j*1.0001234112;
  12.     }
  13.     CTime t2 = CTime::GetCurrentTime();
  14.     CTimeSpan t=t2-t1;
  15.     cout<<t.GetMinutes()<<' '<<t.GetSeconds()<<endl;
  16. }

double类型的次方运算

  1. #include <afxwin.h>
  2. #include <math.h>
  3. #include <iostream>
  4. using namespace std;
  5. //一亿次的开方,结果用了4秒
  6. void main()
  7. {
  8.     CTime t1 = CTime::GetCurrentTime();
  9.     double j = 999999999.999999999;
  10.     for (int i=0;i<100000000;i++)
  11.     {
  12.         sqrt(j);
  13.     }
  14.     CTime t2 = CTime::GetCurrentTime();
  15.     CTimeSpan t=t2-t1;
  16.     cout<<t.GetMinutes()<<' '<<t.GetSeconds()<<endl;
  17. }

double类型的加法运算

  1. #include <afxwin.h> 
  2. #include <iostream> 
  3. using namespace std;
  4. //十亿次加法,用了2秒,如果要测试更大规模,就得使用循环嵌套了:i溢出了!
  5. void main()
  6. {
  7.     CTime t1 = CTime::GetCurrentTime();
  8.     double j =2.345;
  9.     for (int i=0;i<10000000000;i++)
  10.     {
  11.         j+0.2345511;
  12.     }
  13.     CTime t2 = CTime::GetCurrentTime();
  14.     CTimeSpan t=t2-t1;
  15.     cout<<t.GetMinutes()<<' '<<t.GetSeconds()<<endl;
  16. }

double类型的除法运算

  1. #include <afxwin.h> 
  2. #include <iostream> 
  3. using namespace std;
  4. //十亿次除法,用了3秒
  5. void main()
  6. {
  7.     CTime t1 = CTime::GetCurrentTime();
  8.     double j =2.345;
  9.     for (int i=0;i<1000000000;i++)
  10.     {
  11.         j/3.11212;
  12.     }
  13.     CTime t2 = CTime::GetCurrentTime();
  14.     CTimeSpan t=t2-t1;
  15.     cout<<t.GetMinutes()<<' '<<t.GetSeconds()<<endl;
  16. }

当然,如果开启了release模式,运算次数可以有10~100倍的提升。

结论:加法最快,乘法、除法相当;开方最慢,基本上比乘法的运算慢上10倍。