友好地打印耗时

我这个写得会不会有点太复杂了,你们有更好的写法吗?

    private static String printMillis(long x) {
        if (x == 0) {
            return "0 毫秒";
        }

        int[] unit = {1000, 60, 60, 24};
        String[] cunit = {"毫秒", "秒", "分钟", "小时", "天"};
        long[] stack = new long[5];

        for (int i = 0; x != 0 && i < 4; i++) {
            stack[i + 1] = x / unit[i];
            stack[i] = x % unit[i];
            x = stack[i + 1];
        }
        stack[4] = x;

        int start = 4;
        for (; start >= 0; start--) {
            if (stack[start] != 0) break;
        }

        StringBuilder sb = new StringBuilder();
        for (int i = start; i >= 0; i--) {
            sb.append(stack[i]).append(" ").append(cunit[i]).append(" ");
        }
        return sb.toString();
    }
posted @ 2021-08-21 13:34  _lazyval  阅读(42)  评论(0编辑  收藏  举报