Java:计算每秒的性能

时间:2017-06-05 16:29:53

标签: java

我有一个同时执行一些繁重操作的线程池,以下是我的代码

ExampleCompute.java

class ExampleCompute {
   private List<long> allData = new ArrayList<long>();
   ExecutorService executor = Executors.newFixedThreadPool(1000);

   public calculate() {
      for(int i=0; i<myData.size; i++) {
        MyWorker worker = new MyWorker(myData.get(i));
        Future<long> currentDataPoint = executor.submit(worker);
        allData.add(currentDataPoint);
      }

      executor.shutdown();
      while (!executor.isTerminated()) {
      }
   }
}

我要做的是在屏幕上打印每N秒钟每秒完成的操作数量。

例如

// Every 10 seconds do the following
System.out.println("Thread pool is completing 533 calculation per second");

实现这一目标的最佳方式是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用前后方法跟踪时间

public class TrackingThreadPool extends ThreadPoolExecutor {

    private final ThreadLocal<Long> startTime = new ThreadLocal<Long>();
    private volatile long totalTime;
    private volatile long totalTasks;

    public TrackingThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
            BlockingQueue<Runnable> workQueue, ThreadFactory factory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, factory);
    }

    protected void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        startTime.set(new Long(System.currentTimeMillis()));
    }

    protected void afterExecute(Runnable r, Throwable t) {

        long time = System.currentTimeMillis() - startTime.get().longValue();

        synchronized (this) {
            totalTime += time;
            ++totalTasks;
        }

        super.afterExecute(r, t);
    }
}