基于Python的性能优化
一、多线程
在CPU不密集、IO密集的任务下,多线程可以一定程度的提升运行效率。
import threading
import time
import requests
def fetch_url(url: str)->None:
'''根据地址发起请求,获取响应
- url: 请求地址'''
response = requests.get(url)
print(f"{url}: {response.status_code}")
def fetch_urls_sequential(urls:list)->None:
start_time = time.time()
for url in urls:
fetch_url(url)
end_time = time.time()
print(f"使用单线程时间为: {end_time - start_time} 秒n")
def fetch_urls_concurrent(urls:list)->None:
start_time......
暂无评论...