---
title: "程序运行时间的测试"
author: "22cgreen"
date: "2009-09-03T16:24:31Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-09-03T16:24:31Z"
id: 461528
url: "https://cjava.iteye.com/blog/461528"
---

在测试时发现一个类的实例化时间有几百毫秒,测试下发现以下问题.
1)当一个类加载了很多其它的类时,第一次加载是要多点时间,一般好像为:16毫秒左右,如果实例化一次,再去实例化就会发
现几乎不要时间,反正毫秒数显示为0,因此可以认为类在加载一次后,实例化会从中找是否类已加载,如果加载,直接在内存中实例化类,而不要再
加载类文件,然后再实例化,可想而知,容器中保存实例就是加快了实例化的过程,因为类的模板还在.

2)一个类中加载了多个类,而这些类都继承了A,如果其中一个类实例化后,其它的类实例化A时,其时间可以不计.推断,一个JVM中如果存在一个类的模板
其它使用此类的实例都将使用这个模板.
import java.util.*; 
public class RunningTime 
{ 
public static void main(String argc) throws InterruptedException 
{ 
int i=0,j=0; 
long k=0,begin,end,time; 
Date mydate=new Date(); 
begin=mydate.getTime(); 
for (;i<100;i++) 
{ 
for(;j<100;j++) 
{ 
Thread.currentThread().sleep(5); 
k+=i*j; 
} 
} 
Date mydate2=new Date(); 
end=mydate2.getTime(); 
time=end-begin; 

System.out.println(begin+"运行时间为："+time+" "+end); 
} 
} 
计算运算时间的程序