1. 程式人生 > 實用技巧 >【工具】- ActionUtils篇

【工具】- ActionUtils篇

  • 用於量化一些方法的工具
public class ActionUtils {

    /**
     * .ctor
     */
    private ActionUtils() {
    }

    /**
     * 獲取當前執行方法消耗時間毫秒值
     *
     * @param action 執行方法
     * @return 毫秒值
     */
    public static long computeActionCostMilliseconds(Action0 action) {
        //記錄開始時間
        long startTime = System.currentTimeMillis();
        //此處為你呼叫的方法
        action.call();
        //記錄結束時間
        long endTime = System.currentTimeMillis();

        return endTime - startTime;
    }

    /**
     * 獲取當前執行方法消耗時間毫秒值
     *
     * @param action                   執行方法
     * @param elapsedMillisecondsLimit 消耗時間閥值(超過該值將執行loggerAction方法)
     * @param loggerAction             執行方法
     * @return 執行方法的返回值
     */
    public static <T> T computeFuctionCostMilliseconds(Func0<T> action, int elapsedMillisecondsLimit, Action1<Long>
            loggerAction) {

        return computeFuctionCostMilliseconds(action, ms -> ms > elapsedMillisecondsLimit, loggerAction);
    }

    /**
     * 獲取當前執行方法消耗時間毫秒值
     *
     * @param action                       執行方法
     * @param elapsedMillisecondsLimitFunc 消耗時間閥值函式(該函式為True將執行loggerAction方法)
     * @param loggerAction                 執行方法
     * @return 執行方法的返回值
     */
    public static <T> T computeFuctionCostMilliseconds(Func0<T> action,
            Func1<Long, Boolean> elapsedMillisecondsLimitFunc,
            Action1<Long> loggerAction) {
        ActionElapseResult<T> result = computeFuctionCostMilliseconds(action);

        if (loggerAction != null && elapsedMillisecondsLimitFunc.call(result.getElapsedMilliseconds())) {
            loggerAction.call(result.getElapsedMilliseconds());
        }

        return result.getData();
    }

    /**
     * 獲取當前執行方法消耗時間毫秒值
     *
     * @param action 執行方法
     * @return 消費毫秒值及返回結果
     */
    private static <T> ActionElapseResult<T> computeFuctionCostMilliseconds(Func0<T> action) {
        //記錄開始時間
        long startTime = System.currentTimeMillis();
        //此處為你呼叫的方法
        T data = action.call();
        //記錄結束時間
        long endTime = System.currentTimeMillis();
        //new ActionUtils().new ActionElapseResult()
        return new ActionElapseResult<>(endTime - startTime, data);
    }

    /**
     * 執行方法消耗時間及返回結果類
     *
     * @param <T> 返回型別
     */
    private static class ActionElapseResult<T> {
        private long elapsedMilliseconds;
        private T data;

        private ActionElapseResult(long ms, T data) {
            this.data = data;
            this.elapsedMilliseconds = ms;
        }

        private long getElapsedMilliseconds() {
            return elapsedMilliseconds;
        }

        private T getData() {
            return data;
        }
    }
}