Skip to content

Instantly share code, notes, and snippets.

@valexey
Created August 3, 2020 14:39
Show Gist options
  • Save valexey/ff62c75145ee4053262c8bc5fcb18aba to your computer and use it in GitHub Desktop.
Save valexey/ff62c75145ee4053262c8bc5fcb18aba to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
class Worker implements Runnable {
private final float[] data;
private final int startPos;
Worker(float[] array, int start) {
startPos = start;
data = array;
}
@Override
public void run() {
for (int i=0; i<data.length; ++i) {
int j = startPos + i;
data[i] = (float) (data[i] * Math.sin(0.2 + j/5.0)* Math.cos(0.2 + j/5.0) * Math.cos(0.4 + j/2.0));
}
}
}
public class Main {
static final int SIZE = 100_000_000;
public static void main(String[] args) {
for (int i=0; i<100; ++i) {
float[] arr1 = singleThread();
float[] arr2 = doubleThread();
System.out.println(Arrays.equals(arr1, arr2));
}
}
static float[] singleThread() {
long t0 = System.currentTimeMillis();
float[] arr = new float[SIZE];
for (int i=0; i<arr.length; ++i)
arr[i] = 1.0f;
for (int i=0; i<arr.length; ++i)
arr[i] = (float) (arr[i] * Math.sin(0.2 + i/5.0)* Math.cos(0.2 + i/5.0) * Math.cos(0.4 + i/2.0));
long t1 = System.currentTimeMillis();
System.out.println("singleThread dt = " + (t1-t0));
return arr;
}
static float[] doubleThread() {
long t0 = System.currentTimeMillis();
float[] arr = new float[SIZE];
for (int i=0; i<arr.length; ++i)
arr[i] = 1.0f;
final int HSIZE = SIZE/2;
float[] arr1 = new float[HSIZE];
float[] arr2 = new float[HSIZE];
System.arraycopy(arr, 0, arr1, 0, HSIZE);
System.arraycopy(arr, HSIZE, arr2, 0, HSIZE);
Thread th1 = new Thread(new Worker(arr1, 0));
Thread th2 = new Thread(new Worker(arr2, HSIZE));
th1.start();
th2.start();
try {
th1.join();
th2.join();
System.arraycopy(arr1, 0, arr, 0, HSIZE);
System.arraycopy(arr2, 0, arr, HSIZE, HSIZE);
long t1 = System.currentTimeMillis();
System.out.println("doubleThread dt = " + (t1-t0));
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
return arr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment