添加更多线程会提高我的程序的性能吗 [英] Would adding more threads increase the performance of my program

查看:67
本文介绍了添加更多线程会提高我的程序的性能吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我有一个 while 循环,它遍历一堆图片的数组列表,并对它们进行大量处理以更改它们的外观和图像类型,然后将它们写入磁盘.我的问题是添加多个线程来处理图像或保存图像会加快速度,如果是这样,最好的方法是什么.ArrayList images = new ArrayList();//超过500张图片ArrayList 路径 = new ArrayList();int len = images.size();

In my program I have a while loop which iterates through an array list of a bunch of pictures and does a bunch of processing on them to change how they look and their image type and then writes them to the disk. My question is would adding multiple threads to process images or save the images speed things up, if so what would be the best way to go about it. ArrayList images = new ArrayList ();//over 500 images ArrayList paths = new ArrayList (); int len = images.size();

for (int i =0; i < len ; i ++)
{
BufferedImage image  = process (images.get(i))//takes about a second 
ImageIO.write(image, "jpg", new File(getImagePaths().get(i)));


}

推荐答案

你可以将你的列表分成 n 个块,这样你就有了一个 list/n 大小的块,然后你可以让 n 个线程对这些块"进行操作的图像.这样您就可以同时完成更多工作.

You could partition your list into n blocks so that you have blocks of size of list / n, and you could then have n threads operate on these "blocks" of images. This way you have more work that can be done concurrently.

为了解决一些提出的问题,它很可能也会增加 I/O 并发性,因为在单线程运行中它会在第一次未命中和阻塞时出错,然后再次出错以读取第二个图像,等等......在多线程方式中,它将一次阻塞 n 个图像,这允许 I/O 调度程序一次处理更多的 I/O(这通常是一件好事).这意味着即使在单核处理器中也能提高性能,因为 I/O 重叠,并且在 I/O 线程被阻塞的情况下可以在内核上运行更多线程.

To address some things brought up, it would most likely increase I/O concurrency as well because in a single threaded run it would fault on the first miss and block, then fault again to read the 2nd image, etc... In the multi threaded way it would block for n images at a time which allows the I/O scheduler to handle more I/O at a time (which is generally a good thing). This would mean increased performance even in single core processors due to the overlapping of I/O and the availability of more threads to run on the core while the blocked for I/O threads wait.

这篇关于添加更多线程会提高我的程序的性能吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆