我通过传递ipAddress来调用方法,它将返回ipAddress的位置,如Country,City等等.所以我试图看看它为每次调用花了多少时间.所以我在调用方法之前设置了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;
Run Code Online (Sandbox Code Playgroud)
所以这意味着有时需要0毫秒来获得响应.任何建议将不胜感激.
end*_*gin 55
试试这个
long start_time = System.nanoTime();
resp = GeoLocationService.getLocationByIp(ipAddress);
long end_time = System.nanoTime();
double difference = (end_time - start_time) / 1e6;
Run Code Online (Sandbox Code Playgroud)
Cam*_*mpa 27
我非常喜欢(相对)新的java.time库:它非常接近令人敬畏的imho.
您可以通过以下方式计算两个瞬间之间的持续时间:
import java.time.*
Instant before = Instant.now();
// do stuff
Instant after = Instant.now();
long delta = Duration.between(before, after).toMillis(); // .toWhatsoever()
Run Code Online (Sandbox Code Playgroud)
API非常棒,高度可读且直观.
类也是线程安全的.!
参考资料:Oracle Tutorial,Java Magazine
Jon*_*eet 14
不,这并不意味着它花了0毫秒 - 它表明它花费的时间比你测量的时间少currentTimeMillis().那可能是10毫秒或15毫秒.要求计时不是一个好方法; 获得当前时间更合适.
要衡量某些事情需要多长时间,请考虑使用System.nanoTime.这里重点不在于精度更高,而是分辨率更高......但仅在用于测量两次调用之间的时间时.它不能用作"挂钟".
请注意,即使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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的机器上显示大约466纳秒的差异...所以我不可能期望测量比这更快的东西所花费的时间.(其他时间可能大约是这段时间的倍数.)
从 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));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
119227 次 |
| 最近记录: |