Java 以毫秒为单位计算时间差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9707938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculating time difference in Milliseconds
提问by arsenal
I am making a call to a method by passing ipAddress and it will return back the location of ipAddress like Country, City, etc etc. So I was trying to see how much time it is taking for each call. So I set the start_time before making call to method and end_time after making a call. So sometimes I get difference as 0. And resp contains the valid response.
我正在通过传递 ipAddress 调用一个方法,它将返回 ipAddress 的位置,如国家、城市等。所以我想看看每次调用需要多少时间。所以我在调用方法之前设置了 start_time,然后在调用之后设置了 end_time。所以有时我得到的差异为 0。并且 resp 包含有效响应。
long start_time = System.currentTimeMillis();
resp = GeoLocationService.getLocationIp(ipAddress);
long end_time = System.currentTimeMillis();
long difference = end_time-start_time;
So that means sometimes it is taking 0 ms to get the response back. Any suggestions will be appreciated.
所以这意味着有时需要 0 毫秒才能得到响应。任何建议将不胜感激。
采纳答案by endbegin
Try this
尝试这个
long start_time = System.nanoTime();
resp = GeoLocationService.getLocationByIp(ipAddress);
long end_time = System.nanoTime();
double difference = (end_time - start_time) / 1e6;
回答by Jon Skeet
No, it doesn't mean it's taking 0ms - it shows it's taking a smaller amount of time than you can measure with currentTimeMillis()
. That may well be 10ms or 15ms. It's not a good method to call for timing; it's more appropriate for getting the current time.
不,这并不意味着它需要 0 毫秒 - 它表明它花费的时间比您可以用currentTimeMillis()
. 这很可能是 10 毫秒或 15 毫秒。调用时间不是一个好方法;它更适合获取当前时间。
To measure how long something takes, consider using System.nanoTime
instead. The important point here isn't that the precisionis greater, but that the resolutionwill be greater... but onlywhen used to measure the time between two calls. It must notbe used as a "wall clock".
要衡量某件事需要多长时间,请考虑使用System.nanoTime
。这里的重点不是精度更高,而是分辨率会更高……但仅当用于测量两次调用之间的时间时。它不得用作“挂钟”。
Note that even System.nanoTime
just uses "the most accurate timer on your system" - it's worth measuring how fine-grained that is. You can do that like this:
请注意,即使System.nanoTime
只是使用“系统上最准确的计时器” - 也值得衡量它的细粒度。你可以这样做:
public class Test {
public static void main(String[] args) throws Exception {
long[] differences = new long[5];
long previous = System.nanoTime();
for (int i = 0; i < 5; i++) {
long current;
while ((current = System.nanoTime()) == previous) {
// Do nothing...
}
differences[i] = current - previous;
previous = current;
}
for (long difference : differences) {
System.out.println(difference);
}
}
}
On my machine that shows differences of about 466 nanoseconds... so I can't possibly expect to measure the time taken for something quicker than that. (And other times may well be roughly multiples of that amount of time.)
在我的机器上显示大约 466 纳秒的差异......所以我不可能期望测量比这更快的时间。(而其他时间很可能是该时间的大致倍数。)
回答by Erik Ekman
Since Java 1.5, you can get a more precise time value with System.nanoTime()
, which obviously returns nanoseconds instead.
从 Java 1.5 开始,您可以使用 获得更精确的时间值System.nanoTime()
,显然它返回的是纳秒。
There is probably some caching going on in the instances when you get an immediate result.
当您立即获得结果时,可能会进行一些缓存。
回答by AlexR
I do not know how does your PersonalizationGeoLocationServiceClientHelper
works. Probably it performs some sort of caching, so requests for the same IP address may return extremely fast.
我不知道你的PersonalizationGeoLocationServiceClientHelper
作品如何。可能它会执行某种缓存,因此对相同 IP 地址的请求可能会以极快的速度返回。
回答by Lalit Chaudhari
In such a small cases where difference is less than 0 milliseconds you can get difference in nano seconds as well.
在这种差异小于 0 毫秒的小情况下,您也可以获得纳秒级的差异。
System.nanoTime()
回答by R D
You can use
System.nanoTime();
您可以使用
System.nanoTime();
To get the result in readable format, use
TimeUnit.MILLISECONDS or NANOSECONDS
要以可读格式获得结果,请使用
TimeUnit.MILLISECONDS or NANOSECONDS
回答by Campa
I pretty much like the (relatively) new java.timelibrary: it's close to awesome, imho.
我非常喜欢(相对)新的java.time库:它非常棒,恕我直言。
You can calculate a duration between two instants this way:
您可以通过这种方式计算两个瞬间之间的持续时间:
import java.time.*
Instant before = Instant.now();
// do stuff
Instant after = Instant.now();
long delta = Duration.between(before, after).toMillis(); // .toWhatsoever()
API is awesome, highly readable and intuitive.
API 很棒,可读性强且直观。
Classes are thread-safetoo. !
类也是线程安全的。!
References: Oracle Tutorial, Java Magazine
回答by BillS
In the old days (you know, anytime before yesterday) a PC's BIOS timer would "tick" at a certain interval. That interval would be on the order of 12 milliseconds. Thus, it's quite easy to perform two consecutive calls to get the time and have them return a difference of zero. This only means that the timer didn't "tick" between your two calls. Try getting the time in a loop and displaying the values to the console. If your PC and display are fast enough, you'll see that time jumps, making it look as though it's quantized! (Einstein would be upset!) Newer PCs also have a high resolution timer. I'd imagine that nanoTime() uses the high resolution timer.
在过去(您知道,在昨天之前的任何时间),PC 的 BIOS 计时器会以特定时间间隔“滴答”。该间隔大约为 12 毫秒。因此,很容易执行两次连续调用来获取时间并让它们返回零差值。这仅意味着计时器在您的两次通话之间没有“滴答”。尝试在循环中获取时间并将值显示到控制台。如果您的 PC 和显示器足够快,您会看到时间跳跃,使它看起来好像被量化了!(爱因斯坦会不高兴!)较新的个人电脑也有一个高分辨率的计时器。我想 nanoTime() 使用高分辨率计时器。
回答by user2173372
From Java 8 onward you can try the following:
从 Java 8 开始,您可以尝试以下操作:
import java.time.*;
import java.time.temporal.ChronoUnit;
Instant start_time = Instant.now();
// Your code
Instant stop_time = Instant.now();
System.out.println(Duration.between(start_time, stop_time).toMillis());
//or
System.out.println(ChronoUnit.MILLIS.between(start_time, stop_time));