zoukankan      html  css  js  c++  java
  • 记一次简单的关于SimpleDateFormat的优化

    # 有一个有趣的需求:

    (1)预先定义每天24小时不同时间段的电价

    (2) 有一个list<map<timestamp,value>>: timestamp(时间戳);value(耗电量)

    (3) 求电价,也就是遍历list, 判断timestamp是哪个电价,然后相乘

    ## 有趣的地方在于怎么把timestamp转化为只有"HH:mm:ss"的格式(因为电价的定义只有这种格式)

    ## 方案1

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    public class QQ {
    
        public static void main(String[] args) throws ParseException {
            Long ts = 1556606641000L;
            List<Long> list = new ArrayList<Long>();
            for (int i = 0; i < 200000; i++) {
                list.add(ts + i);
            }
    
            Long start = System.currentTimeMillis();
            for (Long e : list) {
                String str = timestampToStr(e, "HH:mm:ss");
                SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                format.parse(str).getTime();
            }
            System.out.println(System.currentTimeMillis() - start);
        }
    
        private static String timestampToStr(Long timestamp, String formatStr) {
            SimpleDateFormat format = new SimpleDateFormat(formatStr);
            Date date = new Date(timestamp);
            return format.format(date);
        }
    }

    ## 上面的代码耗时 1s-1.5s之间(数据量为200000), 结果很不理想

    ## 方案2

    import java.text.ParseException;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.joda.time.LocalTime;
    
    public class QQ {
    
        public static void main(String[] args) throws ParseException {
            Long ts = 1556606641000L;
            List<Long> list = new ArrayList<Long>();
            for (int i = 0; i < 200000; i++) {
                list.add(ts + i);
            }
    
            Long start = System.currentTimeMillis();
            for (Long e : list) {
                LocalTime time = new LocalTime(ts);
            }
            System.out.println(System.currentTimeMillis() - start);
        }
    
    }

    ## 耗时200-300ms左右

  • 相关阅读:
    HDU 2201 熊猫阿波问题==金刚坐飞机问题
    HDU 2100 (模拟进制加法)
    HDU 2151 Worm
    qsort快速排序
    HDU 1007 (最近点对+qsort对结构体的排序!!!)
    HDU 1348 wall (简单凸包)
    HDU 1392 Surround the Trees(凸包模板)
    HDU 1431素数回文
    HDU 2108 Shape of HDU(判断拐点)
    HDU 2857 Mirror and Light(镜面反射模板)
  • 原文地址:https://www.cnblogs.com/lwmp/p/10797551.html
Copyright © 2011-2022 走看看