有时候需要用到计算程序运行的时间,每次都是直接用System.currentTimeMillis()或者另外一个纳秒的.觉得比较麻烦,就写了一个简单的工具,大神勿喷,有好的建议欢迎留言.
旧版本的代码,存在很多不足.
代码语言:javascript复制package com.wk.mothod;
public class MyTimeUtil {
private long time=0;
public void start() {
time=System.currentTimeMillis();
}
public void end(){
time=System.currentTimeMillis()-time;
}
public long endAndGet(){
time=System.currentTimeMillis()-time;
return time;
}
public long getTime(){
return time;
}
public void disp() {
System.out.println("The total time is:" time "ms");
}
public void endAndDisp() {
time=System.currentTimeMillis()-time;
System.out.println("The total time is:" time "ms");
}
}
优化了下,简单添加了一些锁.不会造成一些重复操作,也有一个实际使用的例子.
代码语言:javascript复制package com.wk.mothod;
public class MyTimeUtil {
private long time=0;
private boolean stag=false,etag=false;
private int tag=0;
public void start() {
if(stag==false){
time=System.currentTimeMillis();
stag=true;
}else{
System.out.println("Start failed! Time has started!");
}
}
public void reStart() {
if(stag==true){
time=System.currentTimeMillis();
}else{
System.out.println("ReStart failed! Time hasn't started!");
}
}
public long end(){
if(etag==false&&stag==true){
time=System.currentTimeMillis()-time;
etag=true;
stag=false;
}else{
System.out.println("End failed! Time hasn't started or alread stop!");
}
return time;
}
public long getTime(){
long t=0;
if(stag==true){
return System.currentTimeMillis()-time;//wkupdate 20170725 get time whenever
}else{
System.out.println("Time hasn't started!");
return 0;
}
// return time;
}
public void disp() {
if(etag==true){
System.out.println("The total time is:" time "ms!");
}else{
System.out.println("Time haven't end");
}
}
public void endAndDisp() {
if(etag==false&&stag==true){
time=System.currentTimeMillis()-time;
System.out.println("The total time is:" time "ms!");
etag=true;
stag=false;
}else{
System.out.println("End failed! Time hasn't started or alread stop!");
}
}
public static void main(String [] args){
MyTimeUtil mt=new MyTimeUtil();
mt.reStart();//test for lock.
mt.start();
mt.start();//test for lock.
mt.reStart();//test for lock.
for(long i=0;i<(1<<24);i ){
if(i%(1<<21)==0){
System.out.println(mt.getTime());// get real time everytime.
}
if(i%(1<<23)==0){
mt.disp(); //add to test for lock.
}
}
mt.end();
mt.end();//test for lock.
mt.endAndDisp();//test for lock.
mt.disp();
}
}