华硕x84h网卡驱动,掘客,什么是猎头公司
使用python分析数据,如果使用了正确的数据结构和算法,有时可以大量提高程序的速度。实现此目的的一种方法是使用muiltithreading(多线程)或multiprocessing(多重处理)。
在这篇文章中,我们不会详细讨论多线程或多处理的内部原理。相反,我们举一个例子,编写一个小的python脚本从unsplash下载图像。我们将从一次下载一个图像的版本开始。接下来,我们使用线程来提高执行速度。
简单地说,线程允许您并行地运行程序。花费大量时间等待外部事件的任务通常适合线程化。它们也称为i/o bound任务例如从文件中读写,网络操作或使用api在线下载。让我们来看一个示例,它展示了使用线程的好处。
在本例中,我们希望通过顺序运行程序来查看从unsplash api下载15张图像需要多长时间:
import requests import time img_urls = [ 'https://images.unsplash.com/photo-1516117172878-fd2c41f4a759', 'https://images.unsplash.com/photo-1532009324734-20a7a5813719', 'https://images.unsplash.com/photo-1524429656589-6633a470097c', 'https://images.unsplash.com/photo-1530224264768-7ff8c1789d79', 'https://images.unsplash.com/photo-1564135624576-c5c88640f235', 'https://images.unsplash.com/photo-1541698444083-023c97d3f4b6', 'https://images.unsplash.com/photo-1522364723953-452d3431c267', 'https://images.unsplash.com/photo-1513938709626-033611b8cc03', 'https://images.unsplash.com/photo-1507143550189-fed454f93097', 'https://images.unsplash.com/photo-1493976040374-85c8e12f0c0e', 'https://images.unsplash.com/photo-1504198453319-5ce911bafcde', 'https://images.unsplash.com/photo-1530122037265-a5f1f91d3b99', 'https://images.unsplash.com/photo-1516972810927-80185027ca84', 'https://images.unsplash.com/photo-1550439062-609e1531270e', 'https://images.unsplash.com/photo-1549692520-acc6669e2f0c' ] start = time.perf_counter() #start timer for img_url in img_urls: img_name = img_url.split('/')[3] #get image name from url img_bytes = requests.get(img_url).content with open(img_name, 'wb') as img_file: img_file.write(img_bytes) #save image to disk finish = time.perf_counter() #end timer print(f"finished in {round(finish-start,2)} seconds") #results finished in 23.101926751 seconds
一共用时23秒。
让我们看看pyhton中的线程模块如何显著地改进我们的程序执行:
import time from concurrent.futures import threadpoolexecutor def download_images(url): img_name = img_url.split('/')[3] img_bytes = requests.get(img_url).content with open(img_name, 'wb') as img_file: img_file.write(img_bytes) print(f"{img_name} was downloaded") start = time.perf_counter() #start timer with threadpoolexecutor() as executor: results = executor.map(download_images,img_urls) #this is similar to map(func, *iterables) finish = time.perf_counter() #end timer print(f"finished in {round(finish-start,2)} seconds") #results finished in 5.544147536 seconds
我们可以看到,与不使用线程代码相比,使用线程代码可以显著提高速度。从23秒到5秒。
对于本例,请注意在创建线程时存在开销,因此将线程用于多个api调用是有意义的,而不仅仅是单个调用。
此外,对于密集的计算,如数据处理,图像处理多处理比线程执行得更好。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Python爬虫:Request Payload和Form Data的简单区别说明
浅谈Python中threading join和setDaemon用法及区别说明
Python3-异步进程回调函数(callback())介绍
python继承threading.Thread实现有返回值的子类实例
Python中使用threading.Event协调线程的运行详解
网友评论