算法时间复杂度和真实时间测算
一维度循环 1后面9个0
public class Main {
public static void main(String[] args) {
long l1 = System.currentTimeMillis();
long x = 0;
long N = (long) 1e9;
for (long i = 0; i < N; i++) {
if (i % 2 == 0) {
x += i;
} else {
x -= i;
}
}
long l2 = System.currentTimeMillis();
System.out.println(l2 - l1);
}
}
二维循环
public class Main {
public static void main(String[] args) {
long l1 = System.currentTimeMillis();
long x = 0;
for (long i = 0; i < 10000; i++) {
for (long j = 0; j < 100000; j++) {
x = x+i+j;
}
}
long l2 = System.currentTimeMillis();
System.out.println(l2 - l1);
}
}
三维循环
public class Main {
public static void main(String[] args) {
long l1 = System.currentTimeMillis();
long x = 0;
for (long i = 0; i < 1000; i++) {
for (long j = 0; j < 1000; j++) {
for (long k = 0; k < 1000; k++) {
x = x + i - j + k;
}
}
}
long l2 = System.currentTimeMillis();
System.out.println(l2 - l1);
}
}
快速排序
public class Main {
public static void main(String[] args) {
int N = 39620077; // 数组长度
int[] randomArray = new int[N];
Random random = new Random();
// 填充数组
for (int i = 0; i < N; i++) {
randomArray[i] = random.nextInt(); // 生成随机整数
}
long l1 = System.currentTimeMillis();
Arrays.sort(randomArray);
long l2 = System.currentTimeMillis();
System.out.println(l2 - l1);
}
}
2^N=1000000000, N 约等于 29.90 , 29还行,30,31,32都不行