2008年(3500)
分类:
2008-05-04 19:27:28
public class InlineMe { int counter=0; public void method1() { for(int i=0;i<1000;i ) addCount(); System.out.println("counter=" counter); } public int addCount() { counter=counter 1; return counter; } public static void main(String args[]) { InlineMe im=new InlineMe(); im.method1(); } }
java -Xrunhprof:cpu=times InlineMe 它生成一个java.hprof.txt输出文件。前十个方法类似下面的结果: CPU TIME (ms) BEGIN (total = 510) Thu Jan 28 16:56:15 1999 rank self accum count trace method 1 5.88% 5.88% 1 25 java/lang/Character. 2 3.92% 9.80% 5808 13 java/lang/String.charAt 3 3.92% 13.73% 1 33 sun/misc/Launcher$AppClassLoader.getPermissions 4 3.92% 17.65% 3 31 sun/misc/URLClassPath.getLoader 5 1.96% 19.61% 1 39 java/net/URLClassLoader.access$1 6 1.96% 21.57% 1000 46 InlineMe.addCount 7 1.96% 23.53% 1 21 sun/io/Converters.newConverter 8 1.96% 25.49% 1 17 sun/misc/Launcher$ExtClassLoader.getExtDirs 9 1.96% 27.45% 1 49 java/util/Stack.peek 10 1.96% 29.41% 1 24 sun/misc/Launcher.
public void addCount() { counter=counter 1; } 再次运行profiler: java -Xrunhprof:cpu=times InlineMe 这次,java.hprof.txt的输出应该显得是不同的。 AddCount方法已经消失。它已被内联了! CPU TIME (ms) BEGIN (total = 560) Thu Jan 28 16:57:02 1999 rank self accum count trace method 1 5.36% 5.36% 1 27 java/lang/Character. 2 3.57% 8.93% 1 23 java/lang/System.initializeSystemClass 3 3.57% 12.50% 2 47 java/io/PrintStream. 4 3.57% 16.07% 5808 15 java/lang/String.charAt 5 3.57% 19.64% 1 42 sun/net/www/protocol/file/Handler.openConnection 6 1.79% 21.43% 2 21 java/io/InputStreamReader.fill 7 1.79% 23.21% 1 54 java/lang/Thread. 8 1.79% 25.00% 1 39 java/io/PrintStream.write 9 1.79% 26.79% 1 40 java/util/jar/JarFile.getJarEntry 10 1.79% 28.57% 1 38 java/lang/Class.forName0
class MyLock { static Integer count=new Integer(5); int test=0; public void letslock() { synchronized(count) { test ; } } } public class LockTest { public static void main(String args[]) { MyLock ml=new MyLock(); long time = System.currentTimeMillis(); for(int i=0;i<5000;i ) { ml.letslock(); } System.out.println("Time taken=" (System.currentTimeMillis()-time)); } }
Unix: export JIT_ARGS="trace exclude(InlineMe.addCount InlineMe.method1)" $ java InlineMe Initializing the JIT library ... DYNAMICALLY COMPILING java/lang/System.getProperty mb=0x63e74 DYNAMICALLY COMPILING java/util/Properties.getProperty mb=0x6de74 DYNAMICALLY COMPILING java/util/Hashtable.get mb=0x714ec DYNAMICALLY COMPILING java/lang/String.hashCode mb=0x44aec DYNAMICALLY COMPILING java/lang/String.equals mb=0x447f8 DYNAMICALLY COMPILING java/lang/String.valueOf mb=0x454c4 DYNAMICALLY COMPILING java/lang/String.toString mb=0x451d0 DYNAMICALLY COMPILING java/lang/StringBuffer. mb=0x7d690 >>>> Inlined java/lang/String.length (4)
javac MyClass.java java -Djava.compiler=NONE MyClass or javac MyClass.java java -Djava.compiler="" MyClass