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左右

  • 相关阅读:
    AtCoder Grand Contest 019
    upd 2020.10.31
    ubuntu 自动配置脚本
    linux下gcc、g++不同版本的安装和切换
    fixes for 100% disk usage on Windows 10
    简单聊聊VisualStudio的断点调试
    运算符重载
    设计模式之桥接模式
    使用C#进行数据库增删改查ADO.NET(三)
    使用C#进行数据库增删改查ADO.NET(二)
  • 原文地址:https://www.cnblogs.com/lwmp/p/10797551.html
Copyright © 2011-2022 走看看