我在我的java代码中添加了一段代码来计算完成程序的时间。
final long startTime = System.currentTimeMillis();
和
final long endTime = System.currentTimeMillis();
最后我打印结束时间和开始时间之间的差异。
System.out.println("The total time needed is :" + (endTime - startTime));
但是当我运行程序时,输出显示
The total time needed is :45194
如果时间以毫秒为单位,则为 45.194 秒,但我的程序最多在 3 秒内完成。所以请帮助我理解这个巨大的数字 45194,它是输出。
编辑:
这是完整的代码
package com.example.TestUnit;
import java.util.Scanner;
public class SurfacePeak {
public static void main(String[] args) {
final long startTime = System.currentTimeMillis();
SurfacePeak s = new SurfacePeak();
int l,m,a,b, peak;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the matrix dimensions :");
a = scan.nextInt();
b = scan.nextInt();
int[][] x = new int [a][b];
System.out.println("Enter the elements of the matrix : ");
for(int i=0;i<a;i++) {
for(int j=0;j<b;j++) {
x[i][j] = scan.nextInt();
}
}
l = 0 ; m = b - 1;
peak = s.GetPeak(x, l, m, a, b);
System.out.println("The peak is : " + peak);
final long endTime = System.currentTimeMillis();
System.out.println("The total time needed is :" + (endTime - startTime));
}
private int GetPeak(int[][] y, int l, int m, int a, int b) {
int midCol = (l+m)/2;
int maxRowindex = GetColMax(y,midCol,a);
if(midCol != 0 && midCol != b-1) {
if(y[maxRowindex][midCol - 1] > y[maxRowindex][midCol]) {
m = midCol - 1;
return GetPeak(y,l,m,a,b);
}else if(y[maxRowindex][midCol + 1] > y[maxRowindex][midCol]) {
l = midCol + 1;
return GetPeak(y,l,m,a,b);
}
}else if(a==2 && b == 2 && midCol == 0 || midCol == b-1) {
if(y[maxRowindex][midCol+1] > y[maxRowindex][midCol] && midCol == 0 )
return y[maxRowindex][midCol+1];
else if(midCol == b -1 && y[maxRowindex][midCol-1]>y[maxRowindex][midCol])
return y[maxRowindex][midCol-1];
}
return y[maxRowindex][midCol];
}
private int GetColMax(int[][] a, int mid, int row) {
int max = a[0][mid], maxRow = 0;
for(int i=0; i<row; i++) {
if(a[i][mid] >= max) {
max = a[i][mid];
maxRow = i;
}
}
return maxRow;
}
这也是输出
Enter the matrix dimensions :
4 4
Enter the elements of the matrix :
10 8 10 10 14 56 78 12 90 99 24 300 6 8 1 2
The peak is : 99
The total time needed is :25235
我上次运行时显示 25235 ...这比实际时间要多得多。
编辑:我在用户输入之前开始计时真是太愚蠢了,这是这里的主要问题。
最佳答案
您显示的代码是正确的。尽管查看开始值和停止值以进行验证会很方便。
时钟重置
您的计算机硬件时钟必须在执行期间已更正或重置。
如果您的主机操作系统配置为使用时间服务器 checkin ,则可能会发生这种情况。这种配置如今已成为常态,因为互联网连接非常普遍。
在某些企业 IT 场景中,系统管理员可以远程重置时钟。
System.nanoTime
您可以通过调用 System.nanoTime
来避免时钟重置问题如果您的目标是micro-benchmarking 。该命令利用自某个未指定时刻(通常是 JVM 启动或主机操作系统启动)以来的递增计数。这个纳秒计数不断增加,直到达到 64 位的极限(292 年)。
此计数不与日历相关,不知道日期或时区或与 UTC 的偏移量。
警告:虽然不断增加的数字并不一定精确。当今的传统时钟硬件的精确度不超过微秒(如果是的话)。
JMH 和 JEP 230 用于基准测试
如果您的目标是微型 benchmarking不要追踪历史时刻,请参阅 JMH工具。现在作为一项功能添加到 OpenJDK 12在 JEP 230 。讨论于this article .
关于java - System.currentTimeMillis()方法: returning huge value for execution time then actual execution time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57258294/