统计程序耗时:编写一个程序求100000以内所有整数的和,并统计程序运行时间,(系统程序类System类:static native long currentTimeMillis()返回以毫米为单位的当前时间)
时间: 2024-05-10 13:13:53 浏览: 10
好的,这是一个纯技术问题,我可以回答。下面是求100000以内所有整数的和的Java代码:
```
public class Main {
public static long sum(int n) {
long result = 0;
for (int i = 1; i <= n; i++) {
result += i;
}
return result;
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long result = sum(100000);
long endTime = System.currentTimeMillis();
System.out.println("结果:" + result);
System.out.println("耗时:" + (endTime - startTime) + "毫秒");
}
}
```
程序的关键部分是sum方法,它用一个循环计算了1到给定参数n的所有整数之和,并返回结果。在main方法中,我们用System.currentTimeMillis方法分别记录程序开始和结束时的时间,并计算它们之间的时间差,即程序的运行时间。最后,打印结果和耗时。
相关问题
统计程序耗时:编写一个程序求100000以内所有整数的和,并统计运行时间,static native long currentTimeMillis()
我可以回答这个问题。您可以使用一个for循环来计算100000以内所有整数的和,并在开始和结束时使用System.currentTimeMillis()来计算程序的运行时间。以下是示例代码:
long startTime = System.currentTimeMillis();
int sum = 0;
for (int i = 1; i <= 100000; i++) {
sum += i;
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("100000以内所有整数的和为:" + sum);
System.out.println("程序的运行时间为:" + totalTime + "毫秒。");
.写一段比较耗时的程序段,练习使用 SystemcurrentTimeMillis()方法和SystemnanoTime()方法计算程序段运行的时间。
好的,这是一个使用冒泡排序算法对一个长度为10000的整数数组进行排序的程序段:
```
import java.util.Random;
public class SortTest {
public static void main(String[] args) {
int[] arr = new int[10000];
Random rand = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(10000);
}
long startTime = System.currentTimeMillis();
long startNano = System.nanoTime();
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
long endTime = System.currentTimeMillis();
long endNano = System.nanoTime();
System.out.println("排序完成!");
System.out.println("程序执行时间(毫秒):" + (endTime - startTime));
System.out.println("程序执行时间(纳秒):" + (endNano - startNano));
}
}
```
当程序运行结束后,会输出程序执行的时间(毫秒和纳秒)。
注意:由于计算机系统资源的占用情况不同,程序运行时间会有所浮动,因此仅供参考,不代表实际的运行时间。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)