测试程序耗时的工具类,可以满足:
1、在程序里直接测试代码块的耗时,打印到后台
2、细化代码块,记录每个小功能的耗时,存入表中 直接对比
建表 oracle
-- Create sequence
create sequence tangcq_SEQUENCE
minvalue 1
maxvalue 9999999999999999999999999999
start with 23066
increment by 1
cache 10
order;
--存记录时间的表
CREATE TABLE dateutils_tangcq(
dateutilsid NUMBER(10) not NULL ,
now_star_time VARCHAR2(30), --距离new对象时候的总耗时
now_last_time VARCHAR2(30),--距离上一次记录到这一次记录的间隔
message VARCHAR2(4000)
);
类:
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import com.sunwayworld.framework.dao.ibatis2.Ibatis2SqlMapClientTemplate;
public class DateUtils {
public Date _start; //创建实例时的开始时间
public Date _agoDate;//上一次存入表时的时间
public String message;//自定义备注信息
private Ibatis2SqlMapClientTemplate ibatis2SqlMapClientTemplate;
public DateUtils() {
_start = new Date();
_agoDate=new Date();
}
public DateUtils(String message) {
_start = new Date();
_agoDate=new Date();
this.message=message;
}
//根据自己的项目 需要自己写 获取数据库连接的方法
public DateUtils(Ibatis2SqlMapClientTemplate ibatis2SqlMapClientTemplate) {
_start = new Date();
_agoDate=new Date();
this.ibatis2SqlMapClientTemplate=ibatis2SqlMapClientTemplate;
}
//控制台 直接打印的方法
public void printTime() {
Date _end = new Date();
System.out.println(message+" 当前耗时:" + (diff(_end,_start) / 1000)+"秒");
}
//带备注信息的打印方法
public void printTime(String message2) {
Date _end = new Date();
System.out.println(message+"-"+message2+" 当前耗时:" + (diff(_end,_start) / 1000)+"秒");
}
public void printTime(Date _start) {
Date _end = new Date();
System.out.println(message+" 当前耗时:" + (diff(_end,_start) / 1000)+"秒");
}
private double diff(Date _end,Date _start){
return (double)(_end.getTime() - _start.getTime());
}
//将耗时存入表中 方便查看
public void insertTime(String message2){
Connection conn = null;
Statement stat = null;
try {
conn = ibatis2SqlMapClientTemplate.getDataSource().getConnection();
stat = conn.createStatement();
Date _end = new Date();
String sqlString=" insert into dateutils_tangcq (dateutilsid,now_star_time,now_last_time,message) values(tangcq_SEQUENCE.NEXTVAL,'"+(diff(_end,_start) / 1000)+"秒','"+(diff(_end,_agoDate) / 1000)+"秒','"+message2+"')";
_agoDate=new Date();
stat.executeUpdate(sqlString);
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
stat.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conn.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}