当前位置:网站首页>System.currentTimeMillis() 和 System.nanoTime() 哪个更快?别用错了!
System.currentTimeMillis() 和 System.nanoTime() 哪个更快?别用错了!
2022-07-04 09:35:00 【Java技术栈】
作者:捏造的信仰
来源:https://segmentfault.com/a/1190000041276485
Java有两个取时间戳的方法:System.currentTimeMillis() 和 System.nanoTime(),它们的使用场景是有区别的,当前网上一些文章对于这两个方法的性能讨论存在一些片面的描述,本文希望能给出一个简单的最终答案。
System.currentTimeMillis() 存在性能问题?
答案是否定的。这两个方法性能差异取决于操作系统。
Windows:
在 Windows 下,System.currentTimeMillis() 比 System.nanoTime() 要快很多,这是因为 Windows 系统为前者提供的只是一个缓存变量,而后者则是实时的去硬件底层获取计数。
所以如果你的生产环境是 Windows,请尽可能避免使用
System.nanoTime()。
Linux:
在 Linux 下,两者的执行耗时相差不大,不论是单线程还是多线程。
不同的虚拟机实现会带来性能差异
如今的云主机主要有 Xen 和 KVM 两种实现方式,网上有文章发现它们在取系统时间方面存在性能差异。
当你的虚拟机用的是 Xen 时,取时间的耗时会是 KVM 的十倍以上。不过上文也提供了遇到此类问题该如何解决的方案。
需要写一个专门的类来提升 System.currentTimeMillis() 性能吗?
不需要。那属于画蛇添足。
我的测试代码
我的测试代码如下,没有任何依赖,可以直接用 javac 编译然后运行。读者有兴趣可以试试:
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<Runnable> testing = test -> {
System.out.println("Single thread test:");
test.run();
System.out.println(THREAD_COUNT + " threads test:");
List<Thread> 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);
}
}因为我用的是 Windows,所以执行输出当中 System.nanoTime() 明显非常慢。
具体输出内容我就不放出来了,因为不具有参考价值,大多数生产环境用的是 Linux。
近期热文推荐:
1.1,000+ 道 Java面试题及答案整理(2022最新版)
4.别再写满屏的爆爆爆炸类了,试试装饰器模式,这才是优雅的方式!!
觉得不错,别忘了随手点赞+转发哦!
边栏推荐
- Les différents modèles imbriqués de listview et Pageview avec les conseils de flutter
- PHP student achievement management system, the database uses mysql, including source code and database SQL files, with the login management function of students and teachers
- About the for range traversal operation in channel in golang
- C # use smtpclient The sendasync method fails to send mail, and always returns canceled
- PHP personal album management system source code, realizes album classification and album grouping, as well as album image management. The database adopts Mysql to realize the login and registration f
- 2022-2028 global gasket metal plate heat exchanger industry research and trend analysis report
- Write a jison parser from scratch (2/10): learn the correct posture of the parser generator parser generator
- Hands on deep learning (43) -- machine translation and its data construction
- Exercise 9-1 time conversion (15 points)
- IIS configure FTP website
猜你喜欢

2022-2028 research and trend analysis report on the global edible essence industry

Hands on deep learning (36) -- language model and data set

Hands on deep learning (42) -- bi-directional recurrent neural network (BI RNN)

PHP personal album management system source code, realizes album classification and album grouping, as well as album image management. The database adopts Mysql to realize the login and registration f

2022-2028 global elastic strain sensor industry research and trend analysis report

Hands on deep learning (33) -- style transfer

MATLAB小技巧(25)竞争神经网络与SOM神经网络

华为联机对战如何提升玩家匹配成功几率

品牌连锁店5G/4G无线组网方案

2022-2028 global gasket plate heat exchanger industry research and trend analysis report
随机推荐
Vanishing numbers
百度研发三面惨遭滑铁卢:面试官一套组合拳让我当场懵逼
Get the source code in the mask with the help of shims
浅谈Multus CNI
法向量点云旋转
Launpad | 基礎知識
Kotlin 集合操作汇总
How does idea withdraw code from remote push
Deadlock in channel
2022-2028 global visual quality analyzer industry research and trend analysis report
System.currentTimeMillis() 和 System.nanoTime() 哪个更快?别用错了!
Hands on deep learning (43) -- machine translation and its data construction
Kubernetes CNI 插件之Fabric
Advanced technology management - how to design and follow up the performance of students at different levels
pcl::fromROSMsg报警告Failed to find match for field ‘intensity‘.
MATLAB小技巧(25)竞争神经网络与SOM神经网络
System. Currenttimemillis() and system Nanotime (), which is faster? Don't use it wrong!
Hands on deep learning (42) -- bi-directional recurrent neural network (BI RNN)
Hands on deep learning (35) -- text preprocessing (NLP)
Exercise 7-2 finding the maximum value and its subscript (20 points)