java - I am making a multithreaded application to process an image yet the sequential version is faster, why? -
i having static bufferedimage in threads , letting each thread modify sections of image. processing extremely independent each pixel done separately, yet sequential version faster how fix that?
edit 1: here how code looks like
public static void main(string[] args) throws ioexception, interruptedexception { long startime, endtime; long time; startime = system.currenttimemillis(); //also tried use nano workingthread t1 = new workingthread("input.jpg"); workingthread t2 = new workingthread(); workingthread t3 = new workingthread(); workingthread t4 = new workingthread(); t1.start(); t2.start(); t3.start(); t4.start(); t1.join(); t2.join(); t3.join(); t4.join(); endtime = system.currenttimemillis(); time = endtime - startime; system.out.println("the time consumed in miliseconds " + time); } public class workingthread extends thread { public static bufferedimage img; public static int p; public int nb; public static int width, height; public workingthread(string file) throws ioexception { file f = new file(file); img = imageio.read(f); width = img.getwidth(); height = img.getheight(); p = 1; nb = 0; } public workingthread() { nb = p; p++; } public void run() { int start=nb*height/p; int end = (nb + 1) * height/p; //the image split according y axis in case for(y=start; y < end ; y++) { for(x =0; x<width; x++) { pixel = img.getrgb(x, y); //processing img.setrgb(x, y, pixel); } } }
as comments have pointed out, flaw in benchmark the overhead of thread setup , teardown larger time takes execute code sequentially.
by inserting silly code takes lot of time, below:
//processing (int = 0; < 1000; i++) { pixel = ((~pixel ^ pixel) | pixel) & pixel; } ...inside for x/y loop , increasing max value of i, you'll see multithreaded version faster sequential one.
ps: used image 2500 x 3300 pixels.
Comments
Post a Comment