Progress Estimator

    Jakarta Commons Cookbook这本书中介绍了一个使用回归分析来估计某个工作需要多长时间的例子。 笔者看过之后感觉有些问题(也可能是笔者数学功底不够)。以下是经过笔者修改后的代码。

 

import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang.time.StopWatch;
import org.apache.commons.math.stat.regression.SimpleRegression;

public class ProgressEstimator {
	//
	private StopWatch stopWatch;
	private SimpleRegression regression;
	
	/**
	 * 
	 */
	public ProgressEstimator() {
		this.stopWatch = new StopWatch();
		this.regression = new SimpleRegression();
	}
	
	/**
	 * 
	 */
	public void start() {
		//
		regression.clear();
		
		//
		stopWatch.reset();
		stopWatch.start();
	}
	
	public void stop() {
		//
		stopWatch.stop();
	}
	
	/**
	 * 
	 */
	public void step(int progress) {
		regression.addData(progress, stopWatch.getTime());
	}
	
	public long getElapsedTime() {
		return stopWatch.getTime();
	}
	
	public long getRemainingTime(long total) {
		long r = (long)(regression.getSlope() * total + regression.getIntercept()) - getElapsedTime();
		return r >= 0 ? r : 0;
	}
	
	
	/**
	 * 
	 */
	public static void main(String args[]) {
		//
		ProgressEstimator pe = new ProgressEstimator();
		pe.start();
		
		//
		int count = 1000;
		for(int i = 0; i < count; i++) {
			//
			try {
				Thread.sleep(RandomUtils.nextInt(30));
			} catch(Exception e) {
				break;
			}
			
			//
			if(i % 10 == 9) {
				//
				pe.step(i);
				
				//
				long elapsed = pe.getElapsedTime();
				long estimatedRemaining = pe.getRemainingTime(count);
				long estimatedTotal = elapsed + estimatedRemaining;
				System.out.println("elapsed time: " + elapsed + ", estimated remaining time: " + estimatedRemaining + ", estimated total: " + estimatedTotal);
			}
		}
		pe.stop();
		System.out.println("total elapsed time: " + pe.getElapsedTime());
	}
}

你可能感兴趣的:(Progress Estimator)