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%,为什么呢?
#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%,为什么呢?
运行的硬件和软件环境都一样吗?测试得到的时间是占cpu的时间,还是你启动程序到程序结束用的时间?
BOOL GetProcessTimes(
HANDLE hProcess,
LPFILETIME lpCreationTime,
LPFILETIME lpExitTime,
LPFILETIME lpKernelTime,
LPFILETIME lpUserTime
);嗯