# 有一個有趣的需求:java
(1)預先定義天天24小時不一樣時間段的電價spa
(2) 有一個list<map<timestamp,value>>: timestamp(時間戳);value(耗電量)code
(3) 求電價,也就是遍歷list, 判斷timestamp是哪一個電價,而後相乘orm
## 有趣的地方在於怎麼把timestamp轉化爲只有"HH:mm:ss"的格式(由於電價的定義只有這種格式)blog
## 方案1get
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), 結果很不理想io
## 方案2form
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左右class