我正在并行执行一个图像处理程序,我有4个内核,所以当我在少于5个线程上运行程序时,应该比只运行1个线程的时间有所改进,我想没有任何改进,因为图片可能太小,因此线程会产生开销。所以我使用了8142x2175图像仍然没有任何改进。问题可能来自Eclipse吗?
这是我的图像处理程序的主要部分,我包括其中一个类,你可以看到我正在使用Java并在eclipse上运行它。
public class Main {
public static void main(String[] args) throws IOException {
final File imageFile= new File ("C:\\Users\\user\\Desktop\\Parallel\\pic8142x2175.jpg");
BufferedImage orgImg= ImageIO.read(imageFile);
// the destination buffered image
BufferedImage destImg = new BufferedImage(orgImg.getWidth(), orgImg.getHeight(),
BufferedImage.TYPE_INT_RGB);
// let the user enter number of thread
System.out.println(" please enter number of threads");
Scanner in = new Scanner(System.in);
int nThreads=in.nextInt();
// create the threads
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
// assign each thread with its own runnable
for (int i=0; i<nThreads;i++){
//Runnable gsr = new GreyscaleRunnable(orgImg, i, nThreads,destImg);
//Runnable pr = new PixelateRunnable(orgImg,20,i,nThreads,destImg);
Runnable fr= new FlipRunnable(orgImg,i,nThreads,destImg);
executor.execute(fr);
}// end of for loop
// This will make the executor accept no new threads
// and finish all existing threads in the queue
executor.shutdown();
// Wait until all threads are finish
}
}
FlipRunnable类
public class FlipRunnable implements Runnable{
private BufferedImage img;
private BufferedImage dest;
private int my_rank, thread_count;
// constructor of the class
public FlipRunnable(BufferedImage img,int my_rank,int thread_count,BufferedImage dest) {
this.img=img;
this.my_rank=my_rank;
this.thread_count=thread_count;
this.dest=dest;
}
long startTime = System.currentTimeMillis();
@Override
public void run() {
int localRows = img.getHeight() / thread_count;
int myFirstRow = my_rank * localRows;
int myLastRow = (my_rank + 1) * localRows - 1;
for (int i = myFirstRow; i <= myLastRow; i++) {
for (int j = 0; j < img.getWidth(); j++){
int px = img.getRGB(j, i);
dest.setRGB(img.getWidth() - j - 1, i, px);
}// end of j loop
}// end of i loop
String dstName = "C:\\Users\\user\\Desktop\\Parallel\\funFlipped.jpg";
File dstFile = new File(dstName);
try {
ImageIO.write(dest, "jpg", dstFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Output image: " + dstName);
// the total time
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("time is:"+totalTime);
}
}
答案 0 :(得分:0)
我认为setRGB()
是synchronized
方法的事实几乎没有改进,因此工作线程之间存在很多争用。您需要将图像数据复制到数组并在那里工作。
答案 1 :(得分:0)
随着线程数量的增加,线程之间的OS切换上下文会有更多的努力。
理想情况下,线程数不应大于Runtime.getRuntime().availableProcessors()
。这通常会返回CPU核心数(超线程将返回每个核心2个线程)。
答案 2 :(得分:0)
首先,您正在尝试处理来自所有线程的相同图片!舒尔性能没有任何改善,因为你在同步的dest.setRGB(...)中遇到了瓶颈。
编辑:@Victor Sorokin的评论是对的。