欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java parallel programming to sum long number

程序员文章站 2022-04-01 16:52:49
...

以下代码是我写的,思路基于 上一篇,再次证明 for 循环有点耗费时间。一旦使用了for 循环创建线程,我们无法得到大于 1 的加速比, 也就是说,平行化失败!

   class MyTimer {
    private static long begin;

    public static void time_start(){
        begin = System.nanoTime();
    }

    public static double time_end_milli_seconds(){
        return System.nanoTime()-begin/1e6;

    }

    public static double time_end_seconds(){
        double total_time =  (System.nanoTime()-begin)/1e6;
        return ((double)((int)total_time))/1000;

    }

}

class MySumThread extends Thread{
    public long sum = 0;
    public static int cpu_num = Runtime.getRuntime().availableProcessors();

    public MySumThread(long begin_index) {
        this.begin_index = begin_index;
    }

    public long begin_index;

    @Override
    public void run() {

        for (long i = begin_index; i < 1000000001; i+=4) {
            sum+=i;
        }
    }
}

public class MySumTask{

    public static long sum_result = 0;

    public static int cpu_num = Runtime.getRuntime().availableProcessors();

    public static double linear_sum(){

        MyTimer.time_start();

        long sum = 0;
        for (long i = 0; i < 1000000001; i++) {
            sum+=i;
        }

        double end_time = MyTimer.time_end_seconds();
        System.out.println(" linear_sum : "+sum+" time elapse : "+end_time);

        return end_time;

    }

    public static double parallel_sum() throws InterruptedException {
        MyTimer.time_start();

/*
        for (int i = 0; i < cpu_num; i++) {
            MySumThread thread = new MySumThread(i+1);
            thread.start();
            thread.join();
            sum += thread.sum;
        }  //it's too slow ...the speed up is over 0.6
*/

        MySumThread thread1 = new MySumThread(1);
        thread1.start();

        MySumThread thread2 = new MySumThread(2);
        thread2.start();

        MySumThread thread3 = new MySumThread(3);
        thread3.start();

        MySumThread thread4 = new MySumThread(4);
        thread4.start();


        thread1.join();
        thread2.join();
        thread3.join();
        thread4.join();

        sum_result += thread1.sum + thread2.sum + thread3.sum + thread4.sum;

        double end_time = MyTimer.time_end_seconds();
        System.out.println(" parallel_sum : "+sum_result+" time elapse : "+end_time);
        return end_time;
    }

    public static void main(String[] args) throws InterruptedException {

       System.out.println("speed up : "+linear_sum()/parallel_sum());

    }

}