当前位置:网站首页>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 !
边栏推荐
- 科普达人丨一文看懂阿里云的秘密武器“神龙架构”
- Nine CIO trends and priorities in 2022
- 《吐血整理》保姆级系列教程-玩转Fiddler抓包教程(2)-初识Fiddler让你理性认识一下
- Logstash ~ detailed explanation of logstash configuration (logstash.yml)
- C language: implementation of daffodil number function
- Qt---error: ‘QObject‘ is an ambiguous base of ‘MyView‘
- Unity animation day05
- 程序员怎么才能提高代码编写速度?
- Opencv learning -- arithmetic operation of image of basic operation
- Book of night sky 53 "stone soup" of Apache open source community
猜你喜欢

Talking about Net core how to use efcore to inject multiple instances of a context annotation type for connecting to the master-slave database

Understand Alibaba cloud's secret weapon "dragon architecture" in the article "science popularization talent"

How to decrypt worksheet protection password in Excel file

DC-2靶场搭建及渗透实战详细过程(DC靶场系列)

Model fusion -- stacking principle and Implementation

《吐血整理》保姆级系列教程-玩转Fiddler抓包教程(2)-初识Fiddler让你理性认识一下

Communication mode based on stm32f1 single chip microcomputer

~89 deformation translation

Overview of convolutional neural network structure optimization

Actual combat | use composite material 3 in application
随机推荐
Understand asp Net core - Authentication Based on jwtbearer
DC-2靶场搭建及渗透实战详细过程(DC靶场系列)
Software Engineer vs Hardware Engineer
Ten clothing stores have nine losses. A little change will make you buy every day
Blood cases caused by Lombok use
MySQL - MySQL adds self incrementing IDs to existing data tables
Market trend report, technical innovation and market forecast of China's hair repair therapeutic apparatus
PR FAQ: how to set PR vertical screen sequence?
China's roof ladder market trend report, technological innovation and market forecast
Summary of database 2
Research Report on surgical otorhinolaryngology equipment industry - market status analysis and development prospect prediction
AI system content recommendation issue 24
Variable cannot have type 'void'
165 webmaster online toolbox website source code / hare online tool system v2.2.7 Chinese version
Research Report on market supply and demand and strategy of tetramethylpyrazine industry in China
Recommend 10 excellent mongodb GUI tools
Audio and video technology development weekly | 252
Application of clock wheel in RPC
%F format character
Function test - knowledge points and common interview questions