C++代码:
#include <iostream.h>
#include <windows.h>
#include <winbase.h>void main()
{
int t1 = GetTickCount();
double x, y, tx0, ty0, tx1, ty1, A, B;
int i;
A=-0.01;
B=0.25;
for(x=-2;x<=2;x+=0.001)
{
for(y=-2;y<=2;y+=0.001)
{
tx0 = x;
ty0 = y;
for(i=0;i<200;i++)
{
tx1 = tx0 * tx0 -ty0 * ty0 + A;
ty1 = 2 * tx0 * ty0 + B;
if(tx1 >= 2 || tx1 <= -2)
break;
if(ty1 >= 2 || ty1 <= -2)
break;
if( (tx1 * tx1 +  ty1 * ty1 ) >= 4)
break;
tx0 = tx1;
ty0 = ty1;
}
}
}
int t2 = GetTickCount();
cout << (t2-t1) << endl;
}Java代码:
class JavaTest
{
public static void main(String arg[])
{
long t1 = System.currentTimeMillis();
double x, y, tx0, ty0, tx1, ty1, A, B;
int i;
A=-0.01;
B=0.25;
for(x=-2;x<=2;x+=0.001)
{
for(y=-2;y<=2;y+=0.001)
{
tx0 = x;
ty0 = y;
for(i=0;i<200;i++)
{
tx1 = tx0 * tx0 -ty0 * ty0 + A;
ty1 = 2 * tx0 * ty0 + B;
if(tx1 >= 2 || tx1 <= -2)
break;
if(ty1 >= 2 || ty1 <= -2)
break;
if( (tx1 * tx1 +  ty1 * ty1 ) >= 4)
break;
tx0 = tx1;
ty0 = ty1;
}
}
}
long t2= System.currentTimeMillis();
System.out.println(t2-t1);
}
}C++代码用VC6 -O2编译,Java代码用“java -server JavaTest”运行,我后来还加上vector和ArrayList来测试,都是Java代码快15%~20%,为什么呢?

解决方案 »

  1.   

    你用VC2008编译看看VC6是win95那年代的
      

  2.   

    java是用jdk1.5.0_19编译的class的。
      

  3.   

    1. 没有具体数据不能说明问题,如时间太短的话,时间精度也是个影响因素。2. 硬件平台也是一个因素。如多核CPU,并且java引擎又启用了并行计算的话,这种现象也是有可能的。 例如 你加上的 -server参数,就可以去掉在测试一些,或者改成 -client在对比测试一下看看。  又或者关掉多核,仅启用一个u在对比看看。
      

  4.   

    这有什么疑问的,又不是每个C++程序都比java的效率高
      

  5.   

    1. 没有具体的数据不能说明问题。 如时间太短的话,精度的影响就不得不考虑。2. 硬件平台的影响。 如多核的U, Java引擎又启用了并行计算的话,这个结果不稀奇。 可以多做几个对比测试,如去掉 java后面的 -server 参数;或者换成 -client参数; 多核的话,关掉多余的,仅用单核做测试看看。
      

  6.   

    你是怎么得出快的结论的?
    运行的硬件和软件环境都一样吗?测试得到的时间是占cpu的时间,还是你启动程序到程序结束用的时间?
      

  7.   

    顺便问个问题,怎么计算程序独占CPU的时间?也就是真正程序运行的时间,有什么特别的方法吗?以前看到过,忘记了。
      

  8.   

    linux 有个 time 命令, 可以计算一个程序占用的好几部分(用户空间, 内核空间, CPU, etc)时间, 不知道 windows 有没有对应的命令.
      

  9.   

    The GetProcessTimes function retrieves timing information for the specified process.
    BOOL GetProcessTimes(
      HANDLE hProcess,
      LPFILETIME lpCreationTime,
      LPFILETIME lpExitTime,
      LPFILETIME lpKernelTime,
      LPFILETIME lpUserTime
    );嗯