当前位置:网站首页>System. Currenttimemillis() and system Nanotime (), which is faster? Don't use it wrong!
System. Currenttimemillis() and system Nanotime (), which is faster? Don't use it wrong!
2022-07-04 16:36:00 【Java technology stack】
author : A fabricated belief
source :https://segmentfault.com/a/1190000041276485
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 .
Different virtual machine implementations can lead to performance differences
Today's cloud hosts mainly include Xen and KVM Two ways of implementation , Some articles on the Internet found that they have performance differences in taking system time .
When your virtual machine uses Xen when , Taking time will be KVM More than ten times . However, the above also provides solutions to such problems .
You need to write a special class to improve System.currentTimeMillis() Performance ?
Unwanted . That's painting a snake to add feet .
My test code
My test code is as follows , Without any dependency , It can be used directly javac Compile and run . Readers who are interested can try :
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 in the execution output System.nanoTime()
Obviously very slow .
I won't release the specific output content , Because it has no reference value , Most production environments use Linux.
Recent hot article recommends :
1.1,000+ Avenue Java Arrangement of interview questions and answers (2022 The latest version )
2. Explode !Java Xie Cheng is coming ...
3.Spring Boot 2.x course , It's too complete !
4. Don't write about the explosion on the screen , Try decorator mode , This is the elegant way !!
5.《Java Development Manual ( Song Mountain version )》 The latest release , Download it quickly !
I think it's good , Don't forget to like it + Forward !
边栏推荐
- System.currentTimeMillis() 和 System.nanoTime() 哪个更快?别用错了!
- What is torch NN?
- 时钟轮在 RPC 中的应用
- ECCV 2022放榜了:1629篇论文中选,录用率不到20%
- How to save the contents of div as an image- How to save the contents of a div as a image?
- Common knowledge of unity Editor Extension
- Expression #1 of ORDER BY clause is not in SELECT list, references column ‘d.dept_ no‘ which is not i
- 嵌入式软件架构设计-函数调用
- The vscode waveform curve prompts that the header file cannot be found (an error is reported if the header file exists)
- How was MP3 born?
猜你喜欢
Model fusion -- stacking principle and Implementation
[North Asia data recovery] a database data recovery case where the partition where the database is located is unrecognized due to the RAID disk failure of HP DL380 server
Big God explains open source buff gain strategy live broadcast
[North Asia data recovery] data recovery case of database data loss caused by HP DL380 server RAID disk failure
[hcie TAC] question 5 - 1
对人胜率84%,DeepMind AI首次在西洋陆军棋中达到人类专家水平
Functional interface, method reference, list collection sorting gadget implemented by lambda
~88 running people practice
error: ‘connect‘ was not declared in this scope connect(timer, SIGNAL(timeout()), this, SLOT(up
Nine CIO trends and priorities in 2022
随机推荐
APOC自定义函数和过程
Vscode prompt Please install clang or check configuration 'clang executable‘
Understand asp Net core - Authentication Based on jwtbearer
Digital recognition system based on OpenCV
Model fusion -- stacking principle and Implementation
Understand Alibaba cloud's secret weapon "dragon architecture" in the article "science popularization talent"
Proxifier global agent software, which provides cross platform port forwarding and agent functions
.Net 应用考虑x64生成
Application and Optimization Practice of redis in vivo push platform
Market trend report, technical innovation and market forecast of taillight components in China
Accounting regulations and professional ethics [7]
Penetration test --- database security: detailed explanation of SQL injection into database principle
Vscode setting outline shortcut keys to improve efficiency
error: ‘connect‘ was not declared in this scope connect(timer, SIGNAL(timeout()), this, SLOT(up
[Previous line repeated 995 more times]RecursionError: maximum recursion depth exceeded
对人胜率84%,DeepMind AI首次在西洋陆军棋中达到人类专家水平
Accounting regulations and professional ethics [11]
Final consistency of MESI cache in CPU -- why does CPU need cache
Understand asp Net core - Authentication Based on jwtbearer
Redis' optimistic lock and pessimistic lock for solving transaction conflicts