我也来一个版本,运行时决定累加数目
Scanner scanner = new Scanner(
System.in);
int target = scanner.nextInt();
for (int c = 0; c < 11; c++) {
long startTime = System.currentTimeMillis(); //获取开始时间
long i = 0, sum = 0;
while (i++ < target) {
sum += i;
}
long endTime = System.currentTimeMillis(); //获取结束时间
System.out.format("sum: %d, use time: %f's\r\n", sum,
(endTime - startTime) / 1000.0);
}
//使用sum的方法
long startTime = System.nanoTime(); //获取开始时间
long result = ((1L + target) * target) / 2L; //求和公式
long endTime = System.nanoTime(); //获取结束时间
System.out.format("sum: %d, use time: %f'ms(may be inaccurate due to the kernel)\r\n", result,
(endTime - startTime) / 1000000.0);
output
1000000000
sum: 500000000500000000, use time: 0.647000's
sum: 500000000500000000, use time: 0.647000's
sum: 500000000500000000, use time: 0.648000's
sum: 500000000500000000, use time: 0.645000's
sum: 500000000500000000, use time: 0.645000's
sum: 500000000500000000, use time: 0.643000's
sum: 500000000500000000, use time: 0.644000's
sum: 500000000500000000, use time: 0.642000's
sum: 500000000500000000, use time: 0.642000's
sum: 500000000500000000, use time: 0.644000's
sum: 500000000500000000, use time: 0.645000's
sum: 500000000500000000, use time: 0.000293'ms(may be inaccurate due to the kernel)