Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3252440
  • 博文数量: 530
  • 博客积分: 13360
  • 博客等级: 上将
  • 技术积分: 5473
  • 用 户 组: 普通用户
  • 注册时间: 2006-07-13 13:32
文章分类

全部博文(530)

文章存档

2017年(1)

2015年(2)

2013年(24)

2012年(20)

2011年(97)

2010年(240)

2009年(117)

2008年(12)

2007年(8)

2006年(9)

分类: Java

2011-03-13 11:42:14

在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:2110
10-》start thread time:2297
100-》start thread time:2594
1000-》start thread time:5672
10000-》start thread time:49875
 
结果分析:
1.在Java程序当中,创建对象所花费的时间几乎可以忽略不计
2.打印输出到屏幕因为涉及到IO操作,需要花费一定的时间,约每次0.0218ms,在对系统性能要求不是很高,基本不会影响程序性能的发挥
3.启动大量并发线程需要发费较多的时间,并且虽然线程本身运行时间的长短,花费的时间也直线上升,看来多线程处理并不是线程越多越好,要有一个适当的度才能最大程度的发挥系统的性能,当线程的运行时间更长时可能导致内存越界异常
阅读(1137) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~