Java计算程序运行时间

本文介绍了两种在程序中记录运行时间的方法。一种是通过创建多线程实现定时输出已使用的时间,另一种则是利用System.currentTimeMillis()来获取系统当前时间,进而计算程序的运行耗时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不废话,直接代码。

方法一:多线程法

Thread js_time = new Thread(new PP());
js_time.start();

//执行程序

js_time.stop();

PP类:

class PP implements Runnable {
	public void run() {
		int i = 0;
		while (true) {
			try {
				Thread.sleep(2000);//睡眠2秒
				i = i + 2;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("正在处理......已使用" + i + "秒");
		}
	}
}


方法二:获取System时间

int t1 = (int) System.currentTimeMillis();

//执行程序

int t2 = (int) System.currentTimeMillis();
System.out.println("已完成,耗时:" + Integer.toString(t2 - t1) + "毫秒");

有时间再加注释吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值