multithreading 多线程能提高性能吗?如何?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15292626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 01:21:31  来源:igfitidea点击:

Does multi-threading improve performance? How?

multithreadingperformancecpu-speed

提问by Valentin

I hear everyone talking about how multi-threading can improve performance. I don't believe this, unless there is something I'm missing. If I have an array of 100 elements and traversing it takes 6 seconds. When I divide the work between two threads, the processor would have to go through the same amount of work and therefore time, except that they are working simultaneously but at half the speed. Shouldn't multi threading make it even slower? Since you need additional instructions for dividing the work?

我听到每个人都在谈论多线程如何提高性能。我不相信这一点,除非我遗漏了什么。如果我有一个包含 100 个元素的数组并且遍历它需要 6 秒。当我在两个线程之间分配工作时,处理器将不得不经历相同的工作量和时间,除了它们同时工作但速度减半。多线程不应该让它更慢吗?既然您需要额外的工作分工说明?

回答by suspectus

For a simple task of iterating 100 elements multi-threading the task will not provide a performance benefit.

对于迭代 100 个元素多线程的简单任务,该任务不会提供性能优势。

Iterating over 100 billion elements and do processing on each element, then the use of additional CPU's may well help reduce processing time. And more complicated tasks will likely incur interrupts due to I/O for example. When one thread is sleeping waiting for a peripheral to complete I/O (e.g. a disk write, or a key press from the keyboard), other threads can continue their work.

迭代超过 1000 亿个元素并对每个元素进行处理,然后使用额外的 CPU 可能有助于减少处理时间。例如,更复杂的任务可能会因 I/O 而导致中断。当一个线程正在休眠等待外围设备完成 I/O(例如磁盘写入或键盘按键)时,其他线程可以继续它们的工作。

回答by Albin Sunnanbo

For CPU bound tasks where you have more than one core in your processor you can divide your work on each of your processor core. If you have two cores, split the work on two threads. This way you have to threads working at full speed. However threads are really expensive to create, so you need a pretty big workload to overcome the initial cost of creating the threads.

对于处理器中有多个内核的 CPU 密集型任务,您可以在每个处理器内核上分配工作。如果您有两个内核,则将工作拆分到两个线程上。这样你就必须全速工作。然而,创建线程确实很昂贵,因此您需要相当大的工作量来克服创建线程的初始成本。

You can also use threads to improve appeared performance (or responsiveness) in an interactive application. You run heavy computations on a background thread to avoid blocking UI interactions. Your computations does not complete faster, but your application does not have those "hangs" that make it appear slow and unresponsive.

您还可以使用线程来提高交互式应用程序中的显示性能(或响应能力)。您在后台线程上运行大量计算以避免阻塞 UI 交互。您的计算并没有更快地完成,但您的应用程序没有那些使其看起来缓慢和无响应的“挂起”。