继续上一篇博文《【重新上本科】在实际问题中,内存赋值所拖累的效率(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
完。
转载请注明出处:http://blog.csdn.net/xceman1997/article/details/20643471
【重新上本科】在实际问题中,内存赋值所拖累的效率(java版本),布布扣,bubuko.com
【重新上本科】在实际问题中,内存赋值所拖累的效率(java版本)
原文:http://blog.csdn.net/xceman1997/article/details/20643471