📄 loop.java
字号:
/* WARANTY NOTICE AND COPYRIGHTThis program is free software; you can redistribute it and/ormodify it under the terms of the GNU General Public Licenseas published by the Free Software Foundation; either version 2of the License, or (at your option) any later version.This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU General Public License for more details.You should have received a copy of the GNU General Public Licensealong with this program; if not, write to the Free SoftwareFoundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.Copyright (C) Michael J. Meyermatmjm@mindspring.comspyqqqdia@yahoo.com*//* * Loop.java * * Created on May 3, 2002, 12:35 AM */package Examples.Array;/** <p>Computing the sum over all x[i]*x[j], i,j=0,...,N-1 in * two different loops which do exactly the same operations just * accessing the array elements in different order. Why * are the relative speeds of the loops so dramatically dependent * on N when N is so small the array fits in the L1 data cache???</p> * * @author Michael J. Meyer */public class Loop { public static void main(String[] args) { int N=500; // the array we'll be looping through, 8*N KB double[] x=new double[N]; for(int j=0;j<N;j++)x[j]=0.001; // lets now compute the sum over all x[i]*x[j], // i,j=0,....,N-1 in two ways: double sum=0, s=0; // LOOP_1 // straightforward sum over i<j, times two, plus sum over i=j long before=System.currentTimeMillis(), after, time; // sum over i<j for(int i=0;i<N;i++) for(int j=i+1;j<N;j++)s+=x[i]*x[j]; sum+=s; // add in the sum over i>j (same as sum over i<j) sum+=s; // add in sum over i=j for(int i=0;i<N;i++)sum+=x[i]*x[i]; // now finished, time it after=System.currentTimeMillis(); time=after-before; System.out.println("LOOP_1, time (milliseconds): "+time); System.out.println("Sum = "+sum+"\n\n\n"); // LOOP_2 // Summing over expanding squares i,j<=n, n=0,1,2,...,N-1. sum=0; before=System.currentTimeMillis(); for(int n=0;n<N;n++) { // sum is now the sum over i,j<n, // add in the sum over i=n, j<n s=0; for(int j=0;j<n;j++)s+=x[n]*x[j]; sum+=s; // add in the sum over i<n, j=n - but that's the same as s sum+=s; // add in i=n,j=n sum+=x[n]*x[n]; } // now finished, time it after=System.currentTimeMillis(); time=after-before; System.out.println("LOOP_2, time (milliseconds): "+time); System.out.println("Sum = "+sum+"\n\n\n"); } // end main } // end loop
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -