首页 > 解决方案 > 我应该传递哪些参数来平均分配函数调用之间的工作?

问题描述

我有一个称为doWork(int a, int b, int c, int amount)计算总计算集数量的函数。在我的主要内容中,我确定每个函数调用应该执行多少计算。我需要知道的是如何传递a,b,c,以便对函数的每次调用都会执行它自己的计算部分。

int nprocs = 2;
int total = 10

public static void main() {
    //total number of calculations to compute
    int totalLoad = ((total*total*total)/6)-(total/6);
    //number of calculations per function call
    int workLoad = totalLoad/nproc;


    for(int i = 0; i < nproc; i++) {
        doWork(a, b, c, workLoad);
    }
}

public void doWork(int i,int j,int k, int amount) {
    boolean start = true;

    for(; i < total && amount != 0; i++) {
        if(!start) {
            j = i+1;
        }
        for(; j < total && amount != 0; j++) {
            if(!start) {
                k = j;
            }
            for(; k < total && amount != 0; k++) {
                if(start) {
                    start = false;
                }

                //some calculation here
                System.out.println(format(i,j,k));
                amount--;
            }
        }
    }

每个函数调用都需要处理要进行的总计算的不同子部分。例如:

    nproc = 2
    totalLoad = 6

    Total work:       Function call 1:
    calc 1            calc 1
    calc 2            calc 2
    calc 3            calc 3
    calc 4
    calc 5            Function call 2:  
    calc 6            calc 4
                      calc 5
                      calc 6

此外,是否有更简洁的方法来编写 doWork() 函数。这对我来说似乎很乱。

标签: javaparameter-passingnested-loops

解决方案


推荐阅读