Skip to content

Multithread Efficiency Comparison between Python and PyPy

Multithread performance comparasion between Python3 and PyPy3.

Demo

#!/usr/bin/env python3
import time
from threading import Thread


def factorize(nu):
    for i in range(1, nu + 1):
        if nu % i == 0:
            yield i


class FactorizeThread(Thread):
    def __init__(self, nu):
        super().__init__()
        self.nu = nu
        self.factors = list(factorize(self.nu))


if __name__ == '__main__':
    # series
    numbers = [1536503, 1395999, 1137837, 1162931, 1182120, 1421341, 1543087, 1741235, 1516637, 1852285]
    start = time.time()
    for number in numbers:
        list(factorize(number))
    delta = time.time() - start
    print(f'Took {delta:.3f} seconds')

    # thread parallel
    start = time.time()
    threads = []
    for number in numbers:
        thread = FactorizeThread(number)
        thread.start()
        threads.append(thread)
    for thread in threads:
        thread.join()
    delta = time.time() - start
    print(f'Took {delta:.3f} seconds')

Compare

$ python3 abc.py
Took 0.794 seconds
Took 0.737 seconds

$ pypy3 abc.py
Took 0.072 seconds
Took 0.052 seconds

Reference

  • https://www.python.org
  • https://www.pypy.org

Disclaimer
  1. License under CC BY-NC 4.0
  2. Copyright issue feedback me#imzye.me, replace # with @
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No privacy information is collected here
Try my iOS App