Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Testing Your Computer Speed 103

Benchmarkprogramuses a loop statement to repeatedly perform the fol-
lowing mathematical expression:


double x = Math.sqrt(index);


This statement calls the Math.sqrt()method to find the square root of a
number. You learn how methods work during Hour 11, “Describing What
Your Object Is Like.”


The benchmark you’re creating sees how many times a Java program can
calculate a square root in one minute.


Use NetBeans to create a new empty Java file called Benchmark. Enter the
text of Listing 8.2 and save the program when you’re done.


LISTING 8.2 The Full Source Code of Benchmark.java
1: classBenchmark {
2: public static voidmain(String[] arguments) {
3: longstartTime = System.currentTimeMillis();
4: longendTime = startTime + 60000;
5: longindex = 0;
6: while(true) {
7: doublex = Math.sqrt(index);
8: longnow = System.currentTimeMillis();
9: if (now > endTime) {
10: break;
11: }
12: index++;
13: }
14: System.out.println(index + “ loops in one minute.”);
15: }
16: }


The following things take place in the program:


. Lines 1–2: The Benchmarkclass is declared and the main()block of
the program begins.
. Line 3: The startTimevariable is created with the current time in
milliseconds as its value, measured by calling the
currentTimeMillis()method of Java’s Systemclass.
. Line 4: The endTimevariable is created with a value 60,000 higher
than startTime. Because one minute equals 60,000 milliseconds, this
sets the variable one minute past startTime.
. Line 5: Alongnamed indexis set up with an initial value of 0.

Free download pdf