我使用来自cern.colt.ParallelQuickSort库(http://incanter.org/docs/parallelcolt/api/cern/colt/ParallelQuickSort.html和https://github.com/Danimoth/Parallel-Colt/blob/master/src/cern/colt/ParallelQuickSort.java)的多线程快速排序Java函数。我想测试选择不同线程数时经过多长时间。我使用System.nanoTime()来跟踪运行时间。但是,即使我选择的线程数和未排序的数组在多次运行中相同,运行时间也大不相同。我认为这是因为cern.colt.ParallelQuickSort库中提供的quicksort()没有等待线程完成。我想知道如何编写代码来等待所有线程完成,以便我可以测量库提供的函数之外的运行时间?如下所示:?
ParallelQuickSort qs=new ParallelQuickSort();
long startTime = System.nanoTime();
qs.quickSort(unsorted_array, 0, array_size, comp, number_threads);
//java code to wait for all threads to complete
long time_elapse= System.nanoTime() - startTime;
编辑: 以下是我的代码: 最初,我的代码是运行快速排序,线程数从1到15,阵列大小为2 ^ 10,2 ^ 15,2 ^ 20,2 ^ 25和2 ^ 28,每次运行30次。为了进行调试,我将代码更改为仅使用1个线程运行数组大小= 2 ^ 10并运行10次。
import cern.colt.ParallelQuickSort;
import cern.colt.function.tint.IntComparator;
import cern.colt.Timer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.System.*;
import java.util.*;
public class quick_sort {
static void readData(int dst[], int nitems, int num) throws IOException{
String s="mydata"+Integer.toString(num)+".txt";
//System.out.println(s);
Scanner scanner = new Scanner(new File(s));
int i = 0;
while(scanner.hasNextInt())
{
dst[i++] = scanner.nextInt();
}
}
public static void main(String [ ] args) throws IOException
{
//for(int i=0; i<n;i++) dst[i]=n-i;
/*
System.out.println("Unsorted: ");
for(int i=0; i<n; i++) System.out.print(dst[i]+" ");
System.out.println(" ");
*/
IntComparator comp=new IntComparator(){
public int compare(int a, int b){
if(a>b) return 1;
else if(a<b) return -1;
else return 0;
}
};
int iter=10;
int thread_num=1;
//FileWriter fw = new FileWriter("out.txt");
int num[]={10, 15, 20, 25, 28};
for(int m=0; m<1; m++){
for(int k=1; k<=thread_num; k++){
long estimatedTime=0;
for(int i=0; i<iter; i++){
int n=1<<num[m];
int dst[]=new int[n];
readData(dst, n, num[m]);
ParallelQuickSort qs=new ParallelQuickSort();
long startTime = System.nanoTime();
qs.quickSort(dst, 0, n, comp, k);
long temp= System.nanoTime() - startTime;
estimatedTime+=temp;
System.out.println("Time="+temp*0.000001);
}
System.out.println(num[m]+"Wall Clock Time when thread number="+k+": "+estimatedTime/iter*0.000001);
//fw.write(num[m]+"Wall Clock Time when thread number="+k+": "+estimatedTime/iter*0.000001+'\n');
}
//System.out.println("Sorted: ");
//for(int i=0; i<n; i++) System.out.print(dst[i]+" ");
//System.out.println(" ");
}
//fw.close();
System.out.println("Finish!");
}
}
结果如下所示:
Time=0.755289
Time=0.632124
Time=0.502016
Time=0.502922
Time=0.100524
Time=0.076072
Time=0.073657
Time=0.073355
Time=0.074261
Time=0.076374
10Wall Clock Time when thread number=1: 0.286659
Finish!
答案 0 :(得分:1)
只有在所有线程/子操作完成后,函数ParallelQuickSort.quicksort
才会返回。您无需手动等待直到所有线程都完成。
这可以通过查看代码(查找other.get()
)来确认,并且这是唯一合理的行为。
编辑:测试性能可能很难,请参阅Java Performance Testing和许多其他地方了解详情。