当前位置:网站首页>System. Currenttimemillis() and system Nanotime() which is faster? Most people get the wrong answer!
System. Currenttimemillis() and system Nanotime() which is faster? Most people get the wrong answer!
2022-06-29 13:33:00 【Java technology stack】
Click on the official account ,Java dried food Timely delivery 
author : A fabricated belief
source :https://segmentfault.com/a/1190000041276485
Recommended reading : Don't use System.currentTimeMillis() The statistics took time , too Low,StopWatch Good use of explosion !
Java There are two ways to get a timestamp :System.currentTimeMillis() and System.nanoTime(), Their usage scenarios are different , At present, some articles on the Internet have some one-sided descriptions about the performance of these two methods , This article hopes to give a simple final answer .
System.currentTimeMillis() There are performance issues ?
The answer is No . The performance difference between the two methods depends on the operating system .
Windows:
stay Windows Next ,System.currentTimeMillis() Than System.nanoTime() Much faster , This is because Windows The system only provides a cache variable for the former , The latter is to get the count from the bottom of the hardware in real time .
So if your production environment is Windows, Please avoid using
System.nanoTime().
Linux:
stay Linux Next , There is little difference in the execution time between the two , Whether it's single threaded or multi-threaded . in addition , Multithreaded series of interview questions and answers have been sorted out , WeChat search Java Technology stack , Send it in the background : interview , You can read it online .
Different virtual machine implementations can lead to performance differences
You need to write a special class to improve System.currentTimeMillis() Performance ?
Unwanted . That's painting a snake to add feet .
My test code
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);
}
} Because I'm using Windows, So the execution loses Out of the middle System.nanoTime() Obviously very slow .
I won't release the specific output content , Because it has no reference value , Most production environments use Linux.


Spring Boot After the scheduled task is started , How to stop automatically ?
Java 8 Sort of 10 A pose , What a show !
23 Design mode and Practice ( Very comprehensive )
Spring Boot Protect sensitive configurations 4 Methods !
Face a 5 year Java, Neither thread can exchange data !
Why does Ali recommend LongAdder?
A new technical director : No code writing with headphones ..
Don't use it. System... It's time ,StopWatch Good use of explosion !
Java 18 Official release ,finalize deprecated ..
Spring Boot Admin Born in the sky !
Spring Boot Learning notes , This is so complete !
Focus on Java Technology stack, see more dry goods


obtain Spring Boot Practical notes !
边栏推荐
- Horizon development board configuration network segment
- Matlab to find the limit
- Design of commodity search engine recommendation system
- Hutool tool class learning (continuous update)
- DeeCamp2022正式开营!李开复、张亚勤亲授大师课 | 创新事
- 思科模拟器简单校园网设计,期末作业难度
- Uncover the secret! Pay attention to those machines under the membership system!
- Tree array application (acwing 24224244)
- Simple introduction to matlab
- 如何让 Dapper 支持 DateOnly 类型
猜你喜欢

Huawei machine learning service speech recognition function enables applications to paint "sound" and color
![Equidistant segmentation of surface rivers in ArcGIS [gradient coloring, pollutant diffusion]](/img/05/18fb41f78b9b57175d50dfece65535.png)
Equidistant segmentation of surface rivers in ArcGIS [gradient coloring, pollutant diffusion]

Ordinary users use vscode to log in to SSH and edit the root file

MySQL tuning

iMile 利用 Zadig 多云环境周部署千次,跨云跨地域持续交付全球业务

Don't build the wheel again. It is recommended to use Google guava open source tool class library. It is really powerful!

Exploring the way of automated testing - Preparation

Autonomous and controllable city! Release of the first domestic artiq architecture quantum computing measurement and control system

Tutorial on building pytoch model from zero (V) writing training process -- some basic configurations

Cvpr2022 | reexamine pooling: your receptive field is not the best
随机推荐
六月集训(第29天) —— 分而治之
C语言内存函数
CVPR2022 | 长期行动预期的Future Transformer
leetcode 522. Longest special sequence II
MySQL常用语句和命令汇总
Matlab to find the limit
韩国AI团队抄袭震动学界!1个导师带51个学生,还是抄袭惯犯
LeCun用62页论文公布未来十年研究计划:AI自主智能
【毕业季】这四年一路走来都很值得——老学长の忠告
Memorized Function
CVPR上百人中招新冠,emoji成“呈堂证供”,M2 MBP被曝硬盘降速,今日更多大新闻在此...
从零搭建Pytorch模型教程(五)编写训练过程--一些基本的配置
Cvpr2022 𞓜 future transformer with long-term action expectation
Prometheus 2.28.0 新特性
DeeCamp2022正式开营!李开复、张亚勤亲授大师课 | 创新事
别再重复造轮子了,推荐使用 Google Guava 开源工具类库,真心强大!
GEE——美国LANDFIRE火灾数据集
揭秘!付费会员制下的那些小心机!
成功解决ValueError: Only TF native optimizers are supported in Eager mode
Ordinary users use vscode to log in to SSH and edit the root file