如何在 Java 中以纳秒为单位测量经过时间?
一般情况下,经过时间是指事件从开始点到终止点的持续时间。以下是 Java 中查找经过时间的几种方法 -
nanoTime() 方法以纳秒为单位返回当前时间。以纳秒为单位查找方法执行的经过时间的步骤如下 -
- 使用 nanoTime() 方法获取当前时间。
- 执行所需的方法。
- 再次使用 nanoTime() 方法获取当前时间。
- 最后,找出结束值和开始值之间的差异。
示例
public class Example {
public void test(){
int num = 0;
for(int i=0; i<=50; i++){
num =num+i;
System.out.print(num+", ");
}
}
public static void main(String args[]){
//Start time
long begin = System.nanoTime();
//Starting the watch
new Example().test();
//End time
long end = System.nanoTime();
long time = end-begin;
System.out.println();
System.out.println("Elapsed Time: "+time);
}
}输出
0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time: 1530200
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP