Home > OS >  Does running two scripts in parallel on a dual-core CPU decrease the speed as compared to running th
Does running two scripts in parallel on a dual-core CPU decrease the speed as compared to running th

Time:09-17

I was wondering whether running two scripts on a dual-core CPU (in parallel at the same time) decreases the speed of the codes as compared to running them serially (running at different times or on two different CPUs). What factors should be considered into account while trying to answer this question?

CodePudding user response:

No; assuming the processes can run independently (neither one is waiting on the other one to move forward), they will run faster in parallel than in serial on a multicore system. For example, here's a little script called busy.py:

for i in range(400000000):
    pass

Running this once, on its own:

$ time python busy.py

real    0m6.875s
user    0m6.871s
sys     0m0.004s

Running it twice, in serial:

$ time (python busy.py; python busy.py)

real    0m14.702s
user    0m14.701s
sys     0m0.001s

Running it twice, in parallel (on a multicore system - relying on the OS to assign different cores):

$ time (python busy.py & python busy.py)

real    0m7.849s
user    0m7.843s
sys     0m0.004s

If we run python busy.py & python busy.py or a single-core system, or simulate it with taskset, we get results that looks more like the serial case than the parallel case:

$ time (taskset 1 python busy.py & taskset 1 python busy.py)

real    0m13.057s
user    0m13.035s
sys     0m0.013s

There is some variance in these numbers because, as @tdelaney mentioned, there are other applications competing for my cores and context-switches are occurring. (You can see how many context-switches occurred with /usr/bin/time -v.)

Nonetheless, they get the idea across: running twice in serial necessarily takes twice as long as running once, as does running twice in "parallel" (context-switching) on a single core. Running twice in parallel on two separate cores takes only about as long as running once, because the two processes really can run at the same time. (Assuming they are not waiting on each other, competing for the same resource, etc.)

This is why the multiprocessing module is useful for parallelizable tasks in Python. (threading can also be useful, if the tasks are IO-bound rather than the CPU-bound.)

CodePudding user response:

How Dual Cores Works When Running Scripts

running two separate scripts

if you run one script then another script on a dual core CPU, then weather or not your scripts will run on each of the cores is dependent on your Operating System.

running two separate threads on a dual core CPU then your threads will actually be faster than on a single core.

  • Related