我知道我可以使用 SimpleDateFormat 获取 yyyyMMdd 格式的日期字符串,但它会带来一些成本,当我在我的机器上测试时,需要 2 秒进行 1000 万次操作
因为我可以缓存这个值并在上午 00:00 安排一个计时器并更新这个日期缓存,但我希望我能以一种足够简单的方式获得这个值,这不会引入明确的成本,但是如果我可以的话
我将在 100 万 tps 内调用此操作。
是否有一种简单且足够快速的方法来做到这一点。
最佳答案
我已经在本地检查过了:
1M - ~2.5 秒:
10M - ~49 秒:
public static List<String> convert(Date[] dates) {
List<String> res = new ArrayList<>(dates.length);
for (Date date : dates)
res.add(new SimpleDateFormat("YYYYMMdd", Locale.US).format(date));
return res;
}
1M - ~1.1 秒:
10M - ~26 秒:
public static List<String> convert(Date[] dates) {
List<String> res = new ArrayList<>(dates.length);
DateFormat df = new SimpleDateFormat("YYYYMMdd", Locale.US);
for (Date date : dates)
res.add(df.format(date));
return res;
}
1M - ~1 秒:
10M - ~15.5 秒:
public static List<String> convert3(Date[] dates) throws ExecutionException, InterruptedException {
int size = 1000;
ThreadLocal<SimpleDateFormat> df = ThreadLocal.withInitial(() -> new SimpleDateFormat("YYYYMMdd", Locale.US));
ExecutorService pool = Executors.newFixedThreadPool(10);
List<Future<List<String>>> futures = new ArrayList<>(dates.length);
for (int i = 0; i < dates.length; i += size) {
int ii = i;
futures.add(pool.submit(() -> {
List<String> res = new ArrayList<>(size);
SimpleDateFormat sdf = df.get();
for (int j = 0; j < size && ii + j < dates.length; j++)
res.add(sdf.format(dates[ii + j]));
return res;
}));
}
List<String> res = new ArrayList<>(dates.length);
for (Future<List<String>> future : futures)
res.addAll(future.get());
pool.shutdown();
return res;
}
I need to accumulate some numbers in memory with high tps and then persist them in redis , with ST_{DATANO}
我再想一想。我不知道是否准确,但你可以看看我的想法。不如花很长时间(以毫秒为单位),并删除所有您不关心的部分:时间部分。这是示例:
final long msOneDay = TimeUnit.DAYS.toMillis(1); // milliseconds in one day: 86400000
Date originalDate = new Date(); // e.g. Sat Jan 03 12:36:05 MSK 1987
long dayId = originalDate .getTime() / msOneDay; // 6211, this value you can store in Redis
Date restoredDate = new Date(dayId * msOneDay); // Sat Jan 03 03:00:00 MSK 1987 - correct date without time information
1M - ~1 秒:
10M - ~10.6 秒:
public static List<String> convert(Date[] dates) {
List<String> res = new ArrayList<>(dates.length);
long msOneDay = TimeUnit.DAYS.toMillis(1);
for (Date date : dates)
res.add(String.valueOf(date.getTime() / msOneDay));
return res;
}
关于java - 快速获取 YYYYMMDD 格式的日期数字的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50808853/