gpt4 book ai didi

java - 如何用Java测量执行时间

转载 作者:行者123 更新时间:2023-12-02 01:33:43 27 4
gpt4 key购买 nike

我试图打印下面代码的执行时间,但它总是给我 0 毫秒。我在网上找到了这段代码,想要测量执行情况,所以我在底部添加了几行。

Java:


class MergeSort {
void merge(int nums[], int left, int m, int right) {
int n1 = m - left + 1;
int n2 = right - m;

int Left_part_arra[] = new int[n1];
int Right_part_arra[] = new int[n2];

for (int i = 0; i < n1; ++i)
Left_part_arra[i] = nums[left + i];
for (int j = 0; j < n2; ++j)
Right_part_arra[j] = nums[m + 1 + j];

int i = 0,
j = 0;

int k = left;
while (i < n1 && j < n2) {
if (Left_part_arra[i] <= Right_part_arra[j]) {
nums[k] = Left_part_arra[i];
i++;
} else {
nums[k] = Right_part_arra[j];
j++;
}
k++;
}

while (i < n1) {
nums[k] = Left_part_arra[i];
i++;
k++;
}

while (j < n2) {
nums[k] = Right_part_arra[j];
j++;
k++;
}
}

// merge()
void sort(int nums[], int left, int right) {
if (left < right) {
// Find the middle point
int m = (left + right) / 2;

// Sort first halve
sort(nums, left, m);
// Sort second halve
sort(nums, m + 1, right);

// Merge the sorted halves
merge(nums, left, m, right);
}
}

// Method to test above
public static void main(String args[]) {
MergeSort ob = new MergeSort();
int nums[] = {
7,
-5,
3,
2,
1,
0,
45
};
System.out.println("Original Array:");
System.out.println(Arrays.toString(nums));
ob.sort(nums, 0, nums.length - 1);
System.out.println("Sorted Array:");
System.out.println(Arrays.toString(nums));

long start = System.currentTimeMillis();
long end = System.currentTimeMillis();
System.out.println("Merge took: " + (end - start) + " milliseconds");
}
}

最佳答案

为了使其正常工作,这一行:

long start = System.currentTimeMillis(); 

应该在此行之前:

ob.sort(nums, 0, nums.length-1);

另外,请记住这是测量时间而不是时间复杂度

关于java - 如何用Java测量执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55564137/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com