您的位置:首页 > 编程语言 > Java开发

【重新上本科】在实际问题中,内存赋值所拖累的效率(java版本)

2014-03-07 20:12 323 查看
继续上一篇博文《【重新上本科】在实际问题中,内存赋值所拖累的效率(c++版本)》。由于实际工作中同事的目标语言是java,所以我用相同的程序在java上面又尝试了一下。

先说下结论吧:有效率提升,不过提升幅度远小于在c++上面的效果。

代码如下:

public static void TestCopyingMemCost () throws IOException {
int ARRAYSIZE = 10000000;
// 1. create the fake data
int [] pSource = new int [ARRAYSIZE];
for (int i=0; i<ARRAYSIZE; i++)
{
if (0 == i%2)
pSource[i] = i;
else
pSource[i] = ARRAYSIZE - i;
}
int [] pTmpBuf = new int [ARRAYSIZE];
for (int i=0; i<ARRAYSIZE; i++)
pTmpBuf[i] = 0;

// 2. memory copy and compare, repeat n times
long tBegin1 = System.nanoTime();
double dCopyMemTotalClocks = 0.0;
double dComparingTotalClocks = 0.0;
for (int i=0; i<100; i++)
{
// 2.1 copy the values in memory
long tBegin1_1 = System.nanoTime();
int iTmpBufSize = 0;
for (int j=0; j<ARRAYSIZE; j++)
{
if (0 == pSource[j]%3)
pTmpBuf[iTmpBufSize++] = pSource[j];
}
long tEnd1_1 = System.nanoTime();
dCopyMemTotalClocks += (double)(tEnd1_1 - tBegin1_1) / 1000000000;

// 2.2 compare the items in temp buffer
long tBegin1_2 = System.nanoTime();
double dMax = -1.0;
for (int k=0; k<iTmpBufSize; k++)
{
if (pTmpBuf[k] > dMax)
dMax = pTmpBuf[k];
}
long tEnd1_2 = System.nanoTime();
dComparingTotalClocks += (double)(tEnd1_2 - tBegin1_2) / 1000000000;
}
long tEnd1 = System.nanoTime();
System.out.printf("Baseline time consuming %f\n", (double)(tEnd1 - tBegin1) / 1000000000);
System.out.printf("copying memory time consuming %f\n", dCopyMemTotalClocks);
System.out.printf("comparing value time consuming %f\n", dComparingTotalClocks);

long tBegin2 = System.nanoTime();
for (int i=0; i<100; i++)
{
double dMax = -1.0;
for (int j=0; j<ARRAYSIZE; j++)
{
if (0 == pSource[i]%3)
{
if (pSource[i] > dMax)
dMax = pSource[i];
}
}
}
long tEnd2 = System.nanoTime();
System.out.printf("targeting time consuming %f\n", (double)(tEnd2 - tBegin2) / 1000000000);
}


实验效果如下:

Baseline time consuming 5.693932
copying memory time consuming 5.099133
comparing value time consuming 0.594711
targeting time consuming 5.121151


从5.6s降低到5.12s。在baseline中,分解计时,内存copy的时间是5.09s,的确占比较大的部分;但是在targeting实验中,整体上提升并不大。从网上找了找jvm的资料,也不明所以。就算一个疑问,留到以后在解决吧。

完。

转载请注明出处:http://blog.csdn.net/xceman1997/article/details/20643471
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: