有时我们在做开发的时候需要记录每个任务执行时间,或者记录一段代码执行时间,最简单的方法就是打印当前时间与执行完时间的差值,然后这样如果执行大量测试的话就很麻烦,并且不直观,

如果想对执行的时间做进一步控制,则需要在程序中很多地方修改,目前spring-framework提供了一个StopWatch类可以做类似任务执行时间控制,也就是封装了一个对开始时间,

结束时间记录操作的Java类,当然还有一些其他控制。源码如下:

/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package com.test; import java.text.NumberFormat;
import java.util.LinkedList;
import java.util.List; /**
* Simple stop watch, allowing for timing of a number of tasks,
* exposing total running time and running time for each named task.
*
* <p>Conceals use of <code>System.currentTimeMillis()</code>, improving the
* readability of application code and reducing the likelihood of calculation errors.
*
* <p>Note that this object is not designed to be thread-safe and does not
* use synchronization.
*
* <p>This class is normally used to verify performance during proof-of-concepts
* and in development, rather than as part of production applications.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Sam Brannen
* @since May 2, 2001
*/
public class StopWatch { /**
* Identifier of this stop watch.
* Handy when we have output from multiple stop watches
* and need to distinguish between them in log or console output.
*/
private final String id; private boolean keepTaskList = true; private final List<TaskInfo> taskList = new LinkedList<TaskInfo>(); /** Start time of the current task */
private long startTimeMillis; /** Is the stop watch currently running? */
private boolean running; /** Name of the current task */
private String currentTaskName; private TaskInfo lastTaskInfo; private int taskCount; /** Total running time */
private long totalTimeMillis; /**
* Construct a new stop watch. Does not start any task.
*/
public StopWatch() {
this.id = "";
} /**
* Construct a new stop watch with the given id.
* Does not start any task.
* @param id identifier for this stop watch.
* Handy when we have output from multiple stop watches
* and need to distinguish between them.
*/
public StopWatch(String id) {
this.id = id;
} /**
* Determine whether the TaskInfo array is built over time. Set this to
* "false" when using a StopWatch for millions of intervals, or the task
* info structure will consume excessive memory. Default is "true".
*/
public void setKeepTaskList(boolean keepTaskList) {
this.keepTaskList = keepTaskList;
} /**
* Start an unnamed task. The results are undefined if {@link #stop()}
* or timing methods are called without invoking this method.
* @see #stop()
*/
public void start() throws IllegalStateException {
start("");
} /**
* Start a named task. The results are undefined if {@link #stop()}
* or timing methods are called without invoking this method.
* @param taskName the name of the task to start
* @see #stop()
*/
public void start(String taskName) throws IllegalStateException {
if (this.running) {
throw new IllegalStateException("Can't start StopWatch: it's already running");
}
this.startTimeMillis = System.currentTimeMillis();
this.running = true;
this.currentTaskName = taskName;
} /**
* Stop the current task. The results are undefined if timing
* methods are called without invoking at least one pair
* {@link #start()} / {@link #stop()} methods.
* @see #start()
*/
public void stop() throws IllegalStateException {
if (!this.running) {
throw new IllegalStateException("Can't stop StopWatch: it's not running");
}
long lastTime = System.currentTimeMillis() - this.startTimeMillis;
this.totalTimeMillis += lastTime;
this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime);
if (this.keepTaskList) {
this.taskList.add(lastTaskInfo);
}
++this.taskCount;
this.running = false;
this.currentTaskName = null;
} /**
* Return whether the stop watch is currently running.
*/
public boolean isRunning() {
return this.running;
} /**
* Return the time taken by the last task.
*/
public long getLastTaskTimeMillis() throws IllegalStateException {
if (this.lastTaskInfo == null) {
throw new IllegalStateException("No tasks run: can't get last task interval");
}
return this.lastTaskInfo.getTimeMillis();
} /**
* Return the name of the last task.
*/
public String getLastTaskName() throws IllegalStateException {
if (this.lastTaskInfo == null) {
throw new IllegalStateException("No tasks run: can't get last task name");
}
return this.lastTaskInfo.getTaskName();
} /**
* Return the last task as a TaskInfo object.
*/
public TaskInfo getLastTaskInfo() throws IllegalStateException {
if (this.lastTaskInfo == null) {
throw new IllegalStateException("No tasks run: can't get last task info");
}
return this.lastTaskInfo;
} /**
* Return the total time in milliseconds for all tasks.
*/
public long getTotalTimeMillis() {
return this.totalTimeMillis;
} /**
* Return the total time in seconds for all tasks.
*/
public double getTotalTimeSeconds() {
return this.totalTimeMillis / 1000.0;
} /**
* Return the number of tasks timed.
*/
public int getTaskCount() {
return this.taskCount;
} /**
* Return an array of the data for tasks performed.
*/
public TaskInfo[] getTaskInfo() {
if (!this.keepTaskList) {
throw new UnsupportedOperationException("Task info is not being kept!");
}
return this.taskList.toArray(new TaskInfo[this.taskList.size()]);
} /**
* Return a short description of the total running time.
*/
public String shortSummary() {
return "StopWatch '" + this.id + "': running time (millis) = " + getTotalTimeMillis();
} /**
* Return a string with a table describing all tasks performed.
* For custom reporting, call getTaskInfo() and use the task info directly.
*/
public String prettyPrint() {
StringBuilder sb = new StringBuilder(shortSummary());
sb.append('\n');
if (!this.keepTaskList) {
sb.append("No task info kept");
} else {
sb.append("-----------------------------------------\n");
sb.append("ms % Task name\n");
sb.append("-----------------------------------------\n");
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumIntegerDigits(5);
nf.setGroupingUsed(false);
NumberFormat pf = NumberFormat.getPercentInstance();
pf.setMinimumIntegerDigits(3);
pf.setGroupingUsed(false);
for (TaskInfo task : getTaskInfo()) {
sb.append(nf.format(task.getTimeMillis())).append(" ");
sb.append(pf.format(task.getTimeSeconds() / getTotalTimeSeconds())).append(" ");
sb.append(task.getTaskName()).append("\n");
}
}
return sb.toString();
} /**
* Return an informative string describing all tasks performed
* For custom reporting, call <code>getTaskInfo()</code> and use the task info directly.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder(shortSummary());
if (this.keepTaskList) {
for (TaskInfo task : getTaskInfo()) {
sb.append("; [").append(task.getTaskName()).append("] took ").append(task.getTimeMillis());
long percent = Math.round((100.0 * task.getTimeSeconds()) / getTotalTimeSeconds());
sb.append(" = ").append(percent).append("%");
}
} else {
sb.append("; no task info kept");
}
return sb.toString();
} /**
* Inner class to hold data about one task executed within the stop watch.
*/
public static final class TaskInfo { private final String taskName; private final long timeMillis; TaskInfo(String taskName, long timeMillis) {
this.taskName = taskName;
this.timeMillis = timeMillis;
} /**
* Return the name of this task.
*/
public String getTaskName() {
return this.taskName;
} /**
* Return the time in milliseconds this task took.
*/
public long getTimeMillis() {
return this.timeMillis;
} /**
* Return the time in seconds this task took.
*/
public double getTimeSeconds() {
return this.timeMillis / 1000.0;
}
} /**
* test
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException{
StopWatch first = new StopWatch("First");
first.start("A");
Thread.sleep(200);
first.stop();
first.start("B");
Thread.sleep(200);
first.stop();
first.start("C");
Thread.sleep(120);
first.stop();
System.out.println(first.prettyPrint()); }
}

执行结果如下:

  1. StopWatch 'First': running time (millis) = 516
  2. -----------------------------------------
  3. ms     %     Task name
  4. -----------------------------------------
  5. 00203  039%  A
  6. 00203  039%  B
  7. 00110  021%  C

打印每个任务执行时间,以及占总时间百分比,个人开发测试时挺有用的,可以作为小工具收藏。

一个简单的任务执行时间监视器 StopWatch的更多相关文章

  1. Apache和Spring提供的StopWatch执行时间监视器

    相关阅读 [小家java]java5新特性(简述十大新特性) 重要一跃 [小家java]java6新特性(简述十大新特性) 鸡肋升级 [小家java]java7新特性(简述八大新特性) 不温不火 [小 ...

  2. 应用OpenMP的一个简单的设计模式

    小喵的唠叨话:最近很久没写博客了,一是因为之前写的LSoftmax后馈一直没有成功,所以在等作者的源码.二是最近没什么想写的东西.前两天,在预处理图片的时候,发现处理200w张图片,跑了一晚上也才处理 ...

  3. JMeter基础之一 一个简单的性能测试

    JMeter基础之一 一个简单的性能测试 上一节中,我们了解了jmeter的一此主要元件,那么这些元件如何使用到性能测试中呢.这一节创建一个简单的测试计划来使用这些元件.该计划对应的测试需求. 1)测 ...

  4. [MFC] 梳理一个简单的图片处理桌面软件中用到的MFC控件技巧

     前言 前些天应好友之拖,帮忙设计一个简单的图像处理的小软件.朋友把核心算法封装好了,但是是用openCV类似于console的编程环境,要我在此基础上改成MFC桌面程序.下图是做成之后的效果: 我是 ...

  5. 从一个简单的Java单例示例谈谈并发

    一个简单的单例示例 单例模式可能是大家经常接触和使用的一个设计模式,你可能会这么写 public class UnsafeLazyInitiallization { private static Un ...

  6. 从一个简单的Java单例示例谈谈并发 JMM JUC

    原文: http://www.open-open.com/lib/view/open1462871898428.html 一个简单的单例示例 单例模式可能是大家经常接触和使用的一个设计模式,你可能会这 ...

  7. 基于Spring aop写的一个简单的耗时监控

    前言:毕业后应该有一两年没有好好的更新博客了,回头看看自己这一年,似乎少了太多的沉淀了.让自己做一个爱分享的人,好的知识点拿出来和大家一起分享,一起学习. 背景: 在做项目的时候,大家肯定都遇到对一些 ...

  8. 测试工具之Jmeter(创建一个简单测试用例)

    前面介绍了如何使用badboy录制jmeter脚本,以及如何导入脚本并进行测试 这里介绍下手动创建测试用例,主要步骤如下: 1.创建线程组 第一次打开Jmeter只有一个测试计划,右键“测试计划”选择 ...

  9. 【Java学习笔记】如何写一个简单的Web Service

    本Guide利用Eclipse以及Ant建立一个简单的Web Service,以演示Web Service的基本开发过程: 1.系统条件: Eclipse Java EE IDE for Web De ...

随机推荐

  1. 一个 Sql语句优化的问题- STATISTICS 统计信息

    前段时间,同事遇到一个 Sql语句的问题,一个列表分页功能响应在30 s以上,看数据库里面的数据条数,数据量也不大,相关字段的一些索引也都有,可就是慢.于是找出具体的sql 语句出来分析,分页功能主要 ...

  2. IntelliJ IDEA 远程调试

    远程调试服务器是一个比较实用的技巧,以便我们能够迅速定位线上问题.本文会介绍如何在IntelliJ IDEA中进行远程调试. 配置IntelliJ IDEA 选择Edit Configurations ...

  3. Redis 资源

    一.资源 1.Redis中文网站: http://www.redis.cn/ 2.RedisDesktop http://redisdesktop.com/download

  4. php各种编码集详解和以及在什么情况下进行使用

    字符是各种文字和符号的总称,包括各国家文字.标点符号.图形符号.数字等. 字符集是多个字符的集合,字符集种类较多,每个字符集包含的字符个数不同,常见字符集名称:ASCII字符集.GB2312字符集.B ...

  5. [转载]JavaScript内存分析

    https://github.com/CN-Chrome-DevTools/CN-Chrome-DevTools/blob/master/md/Performance-Profiling/javasc ...

  6. 如何在CentOS 6.5上安装EPEL 源

    EPEL 是什么? EPEL (Extra Packages for Enterprise Linux,企业版Linux的额外软件包) 是Fedora小组维护的一个软件仓库项目,为RHEL/CentO ...

  7. WPF:自定义路由事件的实现

    路由事件通过EventManager,RegisterRoutedEvent方法注册,通过AddHandler和RemoveHandler来关联和解除关联的事件处理函数:通过RaiseEvent方法来 ...

  8. Code First02---CodeFirst配置实体与数据库映射的两种方式

    Code First有两种配置数据库映射的方式,一种是使用数据属性DataAnnotation,另一种是Fluent API. 这两种方式分别是什么呢?下面进行一一解释: DataAnnotation ...

  9. 关于outerWidth()属性

    在写代码的时候,获取元素的宽度通常用到这个属性.此属性具有如下特点: 1.默认情况下,它的值为所有后代元素(含此元素本身)中最大的宽度值. 2.若某后代元素的display属性为none,那么在计算的 ...

  10. Word有用的快捷键

      1.shift+上下左右,可以用键盘从当前光标位置选择文本.可以配合各种其他导航键,比如ctrl+上下左右,Home, End, PageUp/Down. 2.选择文本后,按F2,光标会自动变成虚 ...