Advertisement
TeRackSito

Java Random Integer 0-99 Array optimization

Apr 21st, 2024
749
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.19 KB | None | 0 0
  1. package angel;
  2.  
  3. public class RandomCounterArray extends Thread {
  4.     private int start;
  5.     private int end;
  6.     private long executionTime;
  7.     private int[] results;
  8.  
  9.     public RandomCounterArray(int start, int end) {
  10.         this.start = start;
  11.         this.end = end;
  12.         this.results = new int[100];
  13.     }
  14.  
  15.     public int[] getResults() {
  16.         return results;
  17.     }
  18.  
  19.     public int getLength() {
  20.         int length = 0;
  21.         for (int value : results) {
  22.             length += value;
  23.         }
  24.         return length;
  25.     }
  26.  
  27.     public long getExecutionTime() {
  28.         return executionTime;
  29.     }
  30.  
  31.     private int randomInt() {
  32.         return (int) (Math.random() * 100);
  33.     }
  34.  
  35.     @Override
  36.     public void run() {
  37.         long startTime = System.currentTimeMillis();
  38.         for (int i = start; i <= end; i++) {
  39.             int result = randomInt();
  40.             results[result]++;
  41.         }
  42.         long endTime = System.currentTimeMillis();
  43.         executionTime = endTime - startTime;
  44.     }
  45.  
  46.     public static void main(String[] args) {
  47.         int numbers = 10_000_000;
  48.         int numThreads = 8;
  49.         int numbersPerThread = numbers / numThreads;
  50.  
  51.         RandomCounterArray[] calculators = new RandomCounterArray[numThreads];
  52.         for (int i = 0; i < numThreads; i++) {
  53.             int start = i * numbersPerThread + 1;
  54.             int end = (i + 1) * numbersPerThread;
  55.             calculators[i] = new RandomCounterArray(start, end);
  56.         }
  57.  
  58.         long startTime = System.currentTimeMillis();
  59.         for (RandomCounterArray calculator : calculators) {
  60.             calculator.start();
  61.         }
  62.  
  63.         for (RandomCounterArray calculator : calculators) {
  64.             try {
  65.                 calculator.join();
  66.             } catch (InterruptedException e) {
  67.                 e.printStackTrace();
  68.             }
  69.         }
  70.         long endTime = System.currentTimeMillis();
  71.        
  72.         for (int i = 0; i < calculators.length; i++) {
  73.             System.out.println("Thread " + i + " took " + calculators[i].getExecutionTime() + "ms");
  74.         }
  75.         System.out.println("Time taken: " + (endTime - startTime) + "ms");
  76.     }
  77. }
  78.  
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement