在Java程式中,建立對象、列印輸出到螢幕、啟動線程到底需要發費多長時間?針對這個最基本的問題,做了如下測試:
測試硬體環境:聯想揚天E3100,AMD Sempron 64位 2600+(約1.6Ghz),512M記憶體,80G硬碟
測試軟體環境:Eclipse3.2.2+JDK5.0,直接在Eclipse下運行
測試代碼: public class TestCreatObject ...{
public static void main(String[] args) ...{
long start=System.currentTimeMillis();
for(int i=0;i<10000;i++)...{
String str=new String(""+i );
}
long end1=System.currentTimeMillis();
for(int i=0;i<10000;i++)
System.out.println(i);
long end2=System.currentTimeMillis();
for(int i=0;i<10000;i++)...{
TestThread tt=new TestThread();
tt.start();
}
System.out.println("create object time:"+(end1-start));
System.out.println("print screen time:"+(end2-end1));
System.out.println("start thread time:"+( System.currentTimeMillis()-end2));
}
}
class TestThread extends Thread...{
public void run()...{
// try {
// sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
測試結果:create object time:32
print screen time:218
start thread time:1844
對線程測試時,該線程啟動並執行時間和啟動速度是什麼關係呢?原來的線程本身沒有執行任何東西,現在把屏蔽的代碼開啟,把sleep()的時間分別從1-》10-》100-》1000-》10000,結果如下:1-》start thread time:211010-》start thread time:2297100-》start thread time:25941000-》start thread time:567210000-》start thread time:49875
結果分析:1.在Java程式當中,建立對象所花費的時間幾乎可以忽略不計2.列印輸出到螢幕因為涉及到IO操作,需要花費一定的時間,約每次0.0218ms,在對系統效能要求不是很高,基本不會影響程式效能的發揮3.啟動大量並發線程需要發費較多的時間,並且雖然線程本身已耗用時間的長短,花費的時間也直線上升,看來多執行緒並不是線程越多越好,要有一個適當的度才能最大程度的發揮系統的效能,當線程的已耗用時間更長時可能導致記憶體越界異常