欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

打桩计时

程序员文章站 2022-04-09 21:26:03
...

单线程打桩工具

create() -> ( start() -> stop() ) * n次 -> release() -> prettyPrint()

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.swing.filechooser.FileSystemView;

/**
 * 打桩
 */
public class TimeUtils {

  private static int count = 1;

  /**
   * 桌面路径
   */
  private static String path;

  private static ThreadLocal<TimeWatcher> tl = new ThreadLocal<>();

  static {
    FileSystemView fsv = FileSystemView.getFileSystemView();
    File com = fsv.getHomeDirectory();
    String temppath = com.getPath();
    TimeUtils.path = temppath.replaceAll("\\\\", "/");
  }

  /**
   * 创建一个过程
   * 必需
   *
   * @param processName 过程名
   */
  public static synchronized final void create(String processName) {
    TimeWatcher watcher = new TimeWatcher(processName);
    TimeUtils.tl.set(watcher);
    watcher.begin();
  }

  /**
   * 获得统计信息
   *
   * @return
   */
  public static final String prettyPrint() {
    TimeWatcher watcher = TimeUtils.get();

    String separator = "-----------------------------------------\n";
    StringBuffer stringBuffer = new StringBuffer("Time-consuming Analysis '");
    stringBuffer.append(watcher.getProcessName())
        .append("': \n\nRunning Time (millis) = ")
        .append(watcher.getTotalTime()).append("\n").append(separator)
        .append("ms     \t%     \tTask name\n").append(separator)
        .append(watcher.prettyPrint());

    return stringBuffer.toString();
  }

  /**
   * 终止一个过程
   * 必需
   */
  public static synchronized final void release() {
    TimeWatcher watcher = TimeUtils.get();
    watcher.end();

    TimeUtils.print();

    TimeUtils.tl.set(null);
  }

  /**
   * 开始一个任务
   *
   * @param taskName 任务名
   * @return id 任务唯一标识
   */
  public static final int start(String taskName) {
    TimeWatcher watcher = TimeUtils.get();
    return watcher.start(taskName);
  }

  /**
   * 开始一个任务
   *
   * @param taskName 任务名
   * @param id 任务唯一标识
   */
  public static final void start(String taskName, int id) {
    TimeWatcher watcher = TimeUtils.get();
    watcher.start(taskName, id);
  }

  /**
   * 终止一个任务
   *
   * @param id 任务唯一标识
   */
  public static final void stop(int id) {
    TimeWatcher watcher = TimeUtils.get();
    watcher.stop(id);
  }

  protected static void print() {
    String print = TimeUtils.prettyPrint();

    try {
      StringBuffer buffer = new StringBuffer();
      buffer.append(TimeUtils.path).append("/")
          .append(TimeUtils.get().getProcessName()).append("-")
          .append(TimeUtils.count++).append("-")
          .append(
              new SimpleDateFormat("yyyy-MM-dd HH_mm_ss").format(new Date()))
          .append(".txt");
      FileWriter file = new FileWriter(buffer.toString());
      file.write(print);
      file.flush();
      file.close();
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }

  }

  private static TimeWatcher get() {
    TimeWatcher watcher = TimeUtils.tl.get();
    if (watcher == null) {
      throw new RuntimeException(
          "can not get watcher, please invoke create method first.");
    }
    return watcher;
  }

}

class TimeWatcher {

  private long endTime;

  private final CopyOnWriteArraySet<Integer> idSet =
      new CopyOnWriteArraySet<>();

  /**
   * 过程名
   */
  private final String processName;

  private long startTime;

  private final ConcurrentHashMap<Integer, TimeWatcherUnit> tasks =
      new ConcurrentHashMap<>();

  private long totalTime;

  public TimeWatcher(String processName) {
    this.processName = processName;
  }

  public void begin() {
    this.startTime = System.currentTimeMillis();
  }

  public void end() {
    this.endTime = System.currentTimeMillis();
    this.totalTime = this.endTime - this.startTime;
  }

  public String getProcessName() {
    return this.processName;
  }

  public long getTotalTime() {
    return this.totalTime;
  }

  public String prettyPrint() {
    Collection<TimeWatcherUnit> values = this.tasks.values();
    TimeWatcherUnit[] array = values.toArray(new TimeWatcherUnit[0]);
    Arrays.sort(array);
    StringBuffer buffer = new StringBuffer();
    for (TimeWatcherUnit timeWatcherUnit : array) {
      long unitTime = timeWatcherUnit.getTotalTime();
      double percent = (unitTime * 100D) / this.getTotalTime();

      DecimalFormat formatL = new DecimalFormat("000000");
      DecimalFormat formatD = new DecimalFormat("00.00");
      buffer.append(formatL.format(unitTime)).append("\t")
          .append(formatD.format(percent)).append("%\t")
          .append(timeWatcherUnit.getTaskName()).append("\n");
    }
    return buffer.toString();
  }

  public int start(String taskName) {
    Random random = new Random();
    int nextInt = random.nextInt(100000) + 1000;
    while (this.idSet.contains(nextInt)) {
      nextInt = random.nextInt(100000) + 1000;
    }

    this.start(taskName, nextInt);
    return nextInt;
  }

  public void start(String taskName, int id) {
    if (this.idSet.contains(id)) {
      throw new RuntimeException("duplicate id.");
    }

    this.idSet.add(id);

    TimeWatcherUnit timeWatcherUnit = new TimeWatcherUnit(id, taskName);
    this.tasks.put(id, timeWatcherUnit);

    timeWatcherUnit.begin();
  }

  public void stop(int id) {
    if (!this.idSet.contains(id)) {
      throw new RuntimeException("invalid id.");
    }

    TimeWatcherUnit timeWatcherUnit = this.tasks.get(id);
    timeWatcherUnit.end();
  }

}

class TimeWatcherUnit implements Comparable<TimeWatcherUnit> {

  private long endTime;

  private final int id;

  private long startTime;

  private final String taskName;

  public TimeWatcherUnit(int id, String taskName) {
    super();
    this.id = id;
    this.taskName = taskName;
  }

  public void begin() {
    this.startTime = System.currentTimeMillis();
  }

  @Override
  public int compareTo(TimeWatcherUnit outer) {
    return (int) (this.startTime - outer.getStartTime());
  }

  public void end() {
    this.endTime = System.currentTimeMillis();
  }

  public long getStartTime() {
    return this.startTime;
  }

  public String getTaskName() {
    return this.taskName;
  }

  public long getTotalTime() {
    return this.endTime - this.startTime;
  }

}

相关标签: 性能