为什么我的并行程序比顺序程序慢?我没有看到进程创建开销

时间:2017-05-16 06:43:28

标签: java multithreading parallel-processing

我的顺序java程序比并行版本快。下面是我的并行版本的代码。顺序版本是没有Thread的完全相同的代码。我没有看到过多的进程创建开销,我在一个线程中处理200万次计算而我只有2个线程。但它的顺序版本比这个并行版本快两倍。

在程序中,我试图将两个排序的数组合并为一个大的排序数组,并行合并Merge Sort的概念。

import java.util.Date;

public class MergePP {

    public static final int n = 2000000;


    public static void main(String[] args) {
        Integer[] X = new Integer[n];
        Integer[] Y = new Integer[n];
        Integer[] Z = new Integer[X.length + Y.length];

        /* input sorted lists X and Y */
        for (int i = 0; i < n; i++) {
            X[i] = i * 2;
        }

        for (int i = 0; i < n; i++) {
            Y[i] = 1 + i * 2;
        }

        Date t = new Date();

        Thread threadX = new Thread(() -> {
            int j;
            for (int i = 0; i < X.length; i++) {
                // find the position of x[i] and add to Z
                j = searchY(Y, X[i]);
                Z[i + j] = X[i];
            }
        });

        Thread threadY = new Thread(() -> {
            int m;
            for (int k = 0; k < Y.length; k++) {
                // find the position of Y[k] and add to Z
                m = searchX(X, Y[k]);
                Z[k + m] = Y[k];
            }
        });

        threadX.start();
        threadY.start();

        // wait for thread to complete
        try {
            threadX.join();
            threadY.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Date s = new Date();
        System.out.print("Elapsed Time: ");
        System.out.println(s.getTime() - t.getTime());
    }

    private static Integer searchY(Integer[] arr, int k) {

        int startIndex = 0;

        int endIndex = arr.length - 1;

        while (startIndex <= endIndex) {

            int midIndex = (startIndex + endIndex) / 2;

            if (arr[midIndex] == k) {
                // treat it like a k > arr[midIndex]
                return midIndex + 1;
            } else if (k < arr[midIndex]) {
                endIndex = midIndex - 1;
            } else if (k > arr[midIndex]) {
                startIndex = midIndex + 1;
            }
        }

        return endIndex + 1;
    }

    private static Integer searchX(Integer[] arr, int k) {

        int startIndex = 0;

        int endIndex = arr.length - 1;

        while (startIndex <= endIndex) {

            int midIndex = (startIndex + endIndex) / 2;

            if (arr[midIndex] == k) {
                // treat it like a k < arr[midIndex]
                return midIndex - 1;
            } else if (k < arr[midIndex]) {
                endIndex = midIndex - 1;
            } else if (k > arr[midIndex]) {
                startIndex = midIndex + 1;
            }
        }

        return endIndex + 1;
    }

}

注意:我正在使用带有四核处理器的Mac Book Pro。

0 个答案:

没有答案