1

How does multithreading affect timing of methods? I have a method that looks like:

        NeighborThread[] threads = new NeighborThread[4];
        for (int i = 0; i < vertixCores.length - 1; i++) {

            threads[i] = new NeighborThread(...);
            threads[i].start();
        }

        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
            }
        }

I am timing an algorithm, of which this method is a part of. My timing looks like:

        for (int i = 1; i <= 18; i++) {

            final int  n          = 1 << i;
            long total_time = 0;

            for (int j = 1; j <= 5; j++) {
                final long t0 =  System.nanoTime();
                runAlgorithm();
                long endTime = System.currentTimeMillis();
                total_time += (System.nanoTime() - t0);
            }
            System.out.println("N = " + n + ": " + ((double) total_time / 1000 / 1000 / 1000 / 5) + " s");
        }

Will the timing be accurate? I thought it would be since the algorithm shouldn't proceed until all generated threads have completed.

bayesianpower
  • 93
  • 2
  • 8
  • What is that `endTime` doing there? No benchmark is going to be accurate or anything near accurate with just 5 repetitions with no warm-up. Please read [about micro-benchmarking](https://stackoverflow.com/q/504103/4125191). – RealSkeptic Feb 25 '20 at 17:30
  • So you think for each iteration of i I should just run a few loops j without timing it, and then run 5 loops timed? – bayesianpower Feb 25 '20 at 21:59

0 Answers0