关于Java 获取时间戳的方法,我和同事争论了半天~
阅读本文大概需要 2.8 分钟。
来自:https://segmentfault.com/blog/yidinghe
参考1: https://stackoverflow.com/questions/5839152/why-do-system-nanotime-and-system-currenttimemillis-drift-apart-so-rapidly/5839267#5839267
参考2: http://stas-blogspot.blogspot.com/2012/02/what-is-behind-systemnanotime.html
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class TimePerformance {
public static final int LOOP_COUNT = 9999999;
public static final int THREAD_COUNT = 30;
public static void main(String[] args) {
Runnable millisTest = () -> {
long start = System.currentTimeMillis();
for (int i = 0; i < LOOP_COUNT; i++) {
System.currentTimeMillis();
}
long end = System.currentTimeMillis();
System.out.printf("%s : %f ns per call\n",
Thread.currentThread().getName(), ((double)end - start) * 1000000 / LOOP_COUNT);
};
Runnable nanoTest = () -> {
long start = System.currentTimeMillis();
for (int i = 0; i < LOOP_COUNT; i++) {
System.nanoTime();
}
long end = System.currentTimeMillis();
System.out.printf("%s : %f ns per call\n",
Thread.currentThread().getName(), ((double)end - start) * 1000000 / LOOP_COUNT);
};
Consumer
testing = test -> { System.out.println("Single thread test:");
test.run();
System.out.println(THREAD_COUNT + " threads test:");
List
threads = new ArrayList<>(); for (int i = 0; i < THREAD_COUNT; i++) {
Thread t = new Thread(test);
t.start();
threads.add(t);
}
// Wait for all threads to finish
threads.forEach(thread -> {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
};
System.out.println("//// Test System.nanoTime()");
testing.accept(nanoTest);
System.out.println("//// Test System.currentTimeMillis()");
testing.accept(millisTest);
}
}
推荐阅读:
内容包含Java基础、JavaWeb、MySQL性能优化、JVM、锁、百万并发、消息队列、高性能缓存、反射、Spring全家桶原理、微服务、Zookeeper、数据结构、限流熔断降级......等技术栈!
⬇戳阅读原文领取! 朕已阅
评论