package class0_0_printlnTiming_start; /** * This is a start at reproducing the results shown near the beginning of the quarter on * actual runtimes. It is FAR from complete. * * Early results: System.out.println() is expensive! */ public class Timing { public static final long ITERATIONS = 4_000_000L; public static void main(String[] args) { // timeIt(()-> { // int x = 1; // for(long i = 0; i < ITERATIONS; i++) { // System.out.println("Just a little thing."); // x *=2; // } // System.out.println(x); // }); timeIt(()-> { int x = 1; System.out.println("x = " + x); System.out.println("x = " + x); }); timeIt(()-> { int x = 1; for(long i = 0; i < ITERATIONS; i++) { x *=2; } System.out.println("x = " + x); System.out.println("x = " + x); }); timeIt(()-> { int x = 1; int y = 4; for(long i = 0; i < ITERATIONS; i++) { x *=2; y *=2; } System.out.println("x = " + x); System.out.println("y = " + y); }); timeIt(()-> { int x = 1; for(long i = 0; i < ITERATIONS; i++) { x *=2; } System.out.println("x = " + x); System.out.println("x = " + x); }); timeIt(()-> { int x = 1; System.out.println("x = " + x); System.out.println("x = " + x); }); timeIt(()-> {}); } private static void timeIt(Runnable task) { long startTime = System.nanoTime(); task.run(); long endTime = System.nanoTime(); long totalTime = endTime-startTime; System.out.println("Time taken: "+((totalTime)/1_000_000.) + "ms "); } }