Why is my multi-threading slower than my single threading?

后端 未结 6 1690

I know a couple of people asked a question similar to this, but I can’t find any response that would make me understand why it\'s slower.

So, I made a little console

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 07:07

    Applications will work faster with multiple threads if and only if the processor is a bottleneck. Sometimes your disk or RAM are bottlenecks. Most often it's a database or an external service. Adding multiple threads isn't likely to make the code run faster in those cases, quite the contrary, it will often slow execution due to additional synchronization.

    If you want to make your code run faster, you must first check what makes it run slowly. Profile your code. Locate the bottleneck.

    And remember that Premature optimization is the root of all evil

    In your case the bottleneck - the single most-accessed resource which blocks all actions - is the console output stream. It has a single instance and it works relatively slowly. Even a single core won't be used 100% to print on it as fast as possible.

提交回复
热议问题