Search code examples
multithreadingperformancefactorial

Multithreading on a single core


If I split a factorial program in 2 threads. One calculates the factorial of even numbers upto 100 and the other calculates for the odd numbers. What performance improvements can I expect in the execution time on a single core processor?


Solution

  • You can not expect any performance improvement. In fact, you should expect the program to run significantly slower than the single-threaded version.

    Multithreading generally makes programs run slower, not faster. We are willing to pay that penalty for two reasons:

    1) We can use multi-threading as a way to use the processors of a multi-core machine in parallel, and thereby speed up a big computation.

    I know, I said threads make things slower. Well, that's true. If you implement a parallel computation using two threads and two CPU cores, it will run slower than twice as fast as the single-threaded version, but hopefully, still will be faster than what one thread running on one core can do. If not, then maybe four threads on four cores or eight threads on eight cores will be faster than the single-threaded version.

    2) We can use multi-threading to simplify the design of real-time and soft real-time programs. Real-time and soft real-time programs often must respond to several (or many) different un-synchronized inputs. Having a different thread to wait on each input can make the program easier to read than an event driven program that polls each different input in a big loop.

    It's easier to read because the state variables associated with each independent input can be kept in local variables, which is a familiar idiom for most programmers. Of course, easier to read does not mean easier to write... without subtle bugs, but that's a topic for a different day.