Home Backend Development Python Tutorial Efficiency comparison experiment of single thread, multi-thread and multi-process in Python

Efficiency comparison experiment of single thread, multi-thread and multi-process in Python

Nov 22, 2016 am 10:45 AM
python

Comparative experiment

The data shows that if the multi-threaded process is CPU-intensive, multi-threading will not improve the efficiency much. On the contrary, the efficiency may decrease due to frequent switching of threads. It is recommended to use multi-threading; If it is IO-intensive, the multi-threaded process can use the idle time while waiting for IO blocking to execute other threads to improve efficiency. So we compare the efficiency of different scenarios based on experiments

Efficiency comparison experiment of single thread, multi-thread and multi-process in Python

(1) Introduce the required modules

import requests
import time
from threading import Thread
from multiprocessing import Process
Copy after login

(2) Define CPU-intensive computing functions

def count(x, y):
    # 使程序完成150万计算
    c = 0
    while c < 500000:
        c += 1
        x += x
        y += y
Copy after login

(3) Define IO-intensive file reading and writing functions

def write():
    f = open("test.txt", "w")
    for x in range(5000000):
        f.write("testwrite\n")
    f.close()

def read():
    f = open("test.txt", "r")
    lines = f.readlines()
    f.close()
Copy after login

(4) Define the network request function

_head = {
            &#39;User-Agent&#39;: &#39;Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36&#39;}
url = "http://www.tieba.com"
def http_request():
    try:
        webPage = requests.get(url, headers=_head)
        html = webPage.text
        return {"context": html}
    except Exception as e:
        return {"error": e}
Copy after login

(5) Test the time required for linear execution of IO-intensive operations, CPU-intensive operations, and time required for network request-intensive operations

# CPU密集操作
t = time.time()
for x in range(10):
    count(1, 1)
print("Line cpu", time.time() - t)

# IO密集操作
t = time.time()
for x in range(10):
    write()
    read()
print("Line IO", time.time() - t)

# 网络请求密集型操作
t = time.time()
for x in range(10):
    http_request()
print("Line Http Request", time.time() - t)
Copy after login

Output

CPU-intensive: 95.6059999466, 91.57099986076355 92.52800011634827, 99.96799993515015

IO intensive: 24.25, 21.76699995994568, 21.769999980926514, 22.060999870300293

Network request intensive: 4.519999980926514, 8 .563999891281128, 4.371000051498413, 4.522000074386597, 14.671000003814697

(6) Test the time required for multi-threaded concurrent execution of CPU-intensive operations

counts = []
t = time.time()
for x in range(10):
    thread = Thread(target=count, args=(1,1))
    counts.append(thread)
    thread.start()

e = counts.__len__()
while True:
    for th in counts:
        if not th.is_alive():
            e -= 1
    if e <= 0:
        break
print(time.time() - t)
Copy after login

Output: 99.9240000248, 101.26400017738342, 102.32200002670288

(7) Test the time required for multi-threaded concurrent execution of IO-intensive operations

def io():
    write()
    read()

t = time.time()
ios = []
t = time.time()
for x in range(10):
    thread = Thread(target=count, args=(1,1))
    ios.append(thread)
    thread.start()

e = ios.__len__()
while True:
    for th in ios:
        if not th.is_alive():
            e -= 1
    if e <= 0:
        break
print(time.time() - t)
Copy after login

Output: 25.69700002670288, 24.024000167846 68

(8) Test the time required for multi-threaded concurrent execution of network-intensive operations

t = time.time()
ios = []
t = time.time()
for x in range(10):
    thread = Thread(target=http_request)
    ios.append(thread)
    thread.start()

e = ios.__len__()
while True:
    for th in ios:
        if not th.is_alive():
            e -= 1
    if e <= 0:
        break
print("Thread Http Request", time.time() - t)
Copy after login

Output: 0.7419998645782471, 0.3839998245239258, 0.3900001049041748

(9) Test the time required for multiple processes to concurrently perform CPU-intensive operations

counts = []
t = time.time()
for x in range(10):
    process = Process(target=count, args=(1,1))
    counts.append(process)
    process.start()
e = counts.__len__()
while True:
    for th in counts:
        if not th.is_alive():
            e -= 1
    if e <= 0:
        break
print("Multiprocess cpu", time.time() - t)
Copy after login

Output: 54.342000007629395, 53.437999 963760376

(10) Test the concurrent execution of IO-intensive operations by multiple processes

t = time.time()
ios = []
t = time.time()
for x in range(10):
    process = Process(target=io)
    ios.append(process)
    process.start()

e = ios.__len__()
while True:
    for th in ios:
        if not th.is_alive():
            e -= 1
    if e <= 0:
        break
print("Multiprocess IO", time.time() - t)
Copy after login

Output: 12.509000062942505, 13.059000015258789

(11) Test multi-process concurrent execution of Http request-intensive operations

t = time.time()
httprs = []
t = time.time()
for x in range(10):
    process = Process(target=http_request)
    ios.append(process)
    process.start()

e = httprs.__len__()
while True:
    for th in httprs:
        if not th.is_alive():
            e -= 1
    if e <= 0:
        break
print("Multiprocess Http Request", time.time() - t)
Copy after login

Output: 0.5329999923706055, 0.4760000705718994

Experimental results

Efficiency comparison experiment of single thread, multi-thread and multi-process in Python

Through the above results, we can see:

Multiple threads are IO intensive There doesn't seem to be a big advantage under the type of operation (perhaps the advantage will be reflected if the IO operation task is heavier). Under the CPU-intensive operation, the performance is obviously worse than the single-threaded linear execution, but for network requests, For operations that block threads such as busy waiting, the advantages of multi-threading are very obvious

Multiple processes can show performance advantages in CPU-intensive, IO-intensive, and network request-intensive operations (thread-blocking operations often occur). However, for network request-intensive operations, it is almost the same as multi-threading, but it takes up more resources such as CPU, so in this case, we can choose multi-threading to execute

Efficiency comparison experiment of single thread, multi-thread and multi-process in Python

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can the Python interpreter be deleted in Linux system? Can the Python interpreter be deleted in Linux system? Apr 02, 2025 am 07:00 AM

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

How to solve the problem of Pylance type detection of custom decorators in Python? How to solve the problem of Pylance type detection of custom decorators in Python? Apr 02, 2025 am 06:42 AM

Pylance type detection problem solution when using custom decorator In Python programming, decorator is a powerful tool that can be used to add rows...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Do FastAPI and aiohttp share the same global event loop? Do FastAPI and aiohttp share the same global event loop? Apr 02, 2025 am 06:12 AM

Compatibility issues between Python asynchronous libraries In Python, asynchronous programming has become the process of high concurrency and I/O...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to ensure that the child process also terminates after killing the parent process via signal in Python? How to ensure that the child process also terminates after killing the parent process via signal in Python? Apr 02, 2025 am 06:39 AM

The problem and solution of the child process continuing to run when using signals to kill the parent process. In Python programming, after killing the parent process through signals, the child process still...

See all articles