Reputation: 4448
I wrote a simple program(calculating the number of steps for the numbers 1-10^10 using the collatz conjecture)in both python and c++. They were nearly identical, and neither were written for multithreading. I ran the one in python and according to my system manager, one core went straight to 100% usage, the others staying the same. I ran the c++ program and the cores stayed at their same fluctuating between 10 and 15% usage states, never really changing. They both completed around the same time, within seconds. Could someone explain to me why this is happening?
Upvotes: 0
Views: 186
Reputation: 41546
Python is, in general, quite slow at raw number crunching. This is because it uses its full, general purpose object model for everything, including numbers. You can contrast this with Java and C++, which have "native types" which don't offer any of the niceties of a real class (methods, inheritance, data attributes, etc), but do offer access to the raw speed of the underlying CPU.
So, x = a + b
in C++ generally has far less work to do at runtime than x = a + b
in Python, despite the superficially identical syntax. Python's unified object model is one of the things that makes it comparatively easy to use, but it can have a downside on the raw speed front.
There are multiple alternative approaches to recovering that lost speed:
multiprocessing
or concurrent.futures
to take advantage of multiple cores, or even a distributed computing library to make use of multiple machinesP.S. This is a much better question now that the algorithm is described :)
Upvotes: 3