Java语言程序 例题9.6(秒表)

本文介绍如何设计一个名为Stopwatch的类,包括私有字段startTime和endTime,构造函数、start()、stop()和getElapsedTime()方法,并通过实例演示如何使用它来测量100,000个数字的排序时间,重点在于选择排序算法的执行效率测试。
摘要由CSDN通过智能技术生成

*9.6 (Stopwatch) Design a class named StopWatch. The class contains:

 ■ Private data fields startTime and endTime with getter methods.

 ■ A no-arg constructor that initializes startTime with the current time.

 ■ A method named start() that resets the startTime to the current time.

 ■ A method named stop() that sets the endTime to the current time.

 ■ A method named getElapsedTime() that returns the elapsed time for the

stopwatch in milliseconds.

 Draw the UML diagram for the class and then implement the class. Write a test

program that measures the execution time of sorting 100,000 numbers using

selection sort.

9.6(秒表)设计一个名为Stopwatch的类。该类包含:

■ 使用getter方法的private数据字段startTime和endTime。

■ 使用当前时间初始化startTime的无参数构造函数。

■ 将startTime重置为当前时间的名为start()的方法。

■ 将endTime设置为当前时间的名为stop()的方法。

■ 一个名为getElapsedTime()的方法,该方法返回秒表(毫秒)。

绘制该类的UML图,然后实现该类。编写测试用于测量排序100000个数字的执行时间的程序,使用选择排序。

代码如下:


public class Unite9Test6 
{
	public static void main(String[] args) 
	{
		StopWatch time = new StopWatch();
		int nums[] = new int[100000];
        for(int i = 1; i <=100000; ++i)
            nums[i -1] = (int)((System.currentTimeMillis() / i) % 1000);
        time.start();
        for(int i = 0; i <=99999; ++i)//选择排序
        {
            for(int j = i+1; j < 100000; ++j)
            {
                if(nums[i] > nums[j])
                {
                    int temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
                }
            }
        }
        time.stop();
        System.out.println(time.getElapsedTime());


	}
}
class StopWatch
{
	private long startTime ;
	private long endTime ;
	public long getStartTime() {
		return startTime;
	}
	public void setStartTime(long startTime) {
		this.startTime = startTime;
	}
	public long getEndTime() {
		return endTime;
	}
	public void setEndTime(long endTime) {
		this.endTime = endTime;
	}
	public void start() 
	{
		startTime = System.currentTimeMillis();//System.currentTimeMillis()用来获取当前的总毫秒数,
	}
	public void stop() 
	{
		endTime = System.currentTimeMillis();
	}
	public long getElapsedTime() 
	{
		return endTime - startTime;
	}
}

结果如下:

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

差劲的厉害了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值