Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Task for school: Set up a benchmark where you call the access function with a larger and larger n. Code is given, cannot be changed but can be added to where asked to fill in code. I have done this to my best ability.

I need help with calling the access function. What I have written does not work and right now I cannot run this code. Anyone know why?

What I have tried:

Java
import java.util.Random;

public class final1
{
    private static double access(int n) {
        int k = 1_000_000;
        int l = n;
        Random rnd = new Random();
        int[] indx = new int[l];
        // fill the indx array with random number from 0 to n (not including n)
        for (int i = 0; i < l; i++) {
            indx[i] = rnd.nextInt(n);
        }

        int[] array = new int[n];
        // fill the array with dummy values (why not 1)
        for (int i = 0; i < array.length; i++) {
            array[i] = i;
        }
        int sum = 0;
        long t0 = System.nanoTime();
        for (int j = 0; j < k; j++) {
            for (int i = 0; i < l; i++) {
                // access the array with the index given by indx[i]
                indx[i] = i;
                // sum up the result
                sum += indx[i];
            }
        }
        long t_access = (System.nanoTime() - t0);
        t0 = System.nanoTime();
        // do the same loop iteration but only do a dummy add operation
        for (int j = 0; j < k; j++)
        {
            for (int i = 0; i < l; i++) {
                // access the array with the index given by indx[i]
                indx[i] = i;
                // sum up the result
                sum++;
            }
        }
            long t_dummy = (System.nanoTime() - t0);
            return ((double) (t_access - t_dummy)) / ((double) k * (double) l);
        }

        public static void main(String[] args)
        {
            System.out.println(" resolution " + final1.t_access() + " nanoseconds");
        }
    }
Posted
Updated 1-Sep-22 8:02am
v2

1 solution

Quote:
I need help with calling the access function
What's wrong with
Java
public static void main(String[] args)
{
    System.out.println(" resolution " + final1.access(42) + " nanoseconds");
}
?
 
Share this answer
 
Comments
boabaloo 1-Sep-22 15:37pm    
Well I don't know where 42 is coming from so I'm assuming n is the problem here. I have added a value for n now so final1.access(n) is working.
CPallini 1-Sep-22 16:58pm    
https://simple.wikipedia.org/wiki/42_(answer)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900