我们先来复习下协程和线程的定义
协程 ,又称为微线程,它是实现多任务的另一种方式,只不过是比线程更小的执行单元。因为它自带CPU的上下文,这样只要在合适的时机,我们可以把一个协程切换到另一个协程。
线程,有时被称为轻量进程,是程序执行流的最小单元。
比较:
在实现多任务时, 线程切换__从系统层面__远不止保存和恢复CPU上下文这么简单。操作系统为了程序运行的高效性,每个线程都有自己缓存Cache等等数据,操作系统还会帮你做这些数据的恢复操作,所以线程的切换非常耗性能。但是__协程的切换只是单纯地操作CPU的上下文__,所以一秒钟切换个上百万次系统都抗的住。
运用协程 能够使我们工作变得更有效率。
下面是例子:
#!usr/bin/env python #-*- coding:utf-8 _*- """ @author:Administrator @file: 协程.py @time: 2020/2/20 19:12 """ from gevent import monkey;monkey.patch_all() #(必须用到猴子补丁) import gevent import requests import time import pymysql """使用协程向mysql插入10000条数据""" def data_handler(anum,num): conn = pymysql.connect(host=‘127.0.0.1‘,user=‘root‘,password=‘root‘,database=‘python_scrapy‘,charset=‘utf8‘) cursor = conn.cursor() for i in range(anum,num): sql = ‘insert into btree(sid,name,email) values(%s,%s,concat(%s,"hael","@163"));‘ res = cursor.execute(sql,[i,"root",i]) conn.commit() cursor.close() conn.close() start_time=time.time() gevent.joinall([ gevent.spawn(data_handler,1,2000), gevent.spawn(data_handler,2001,5000), gevent.spawn(data_handler,5001,8000), gevent.spawn(data_handler,8001,10000), ]) stop_time=time.time() print(‘run time is %s‘ %(stop_time-start_time)) #output : run time is 2.826383113861084
从上面可以看出向数据库插入10000条数据我们用了
2.826383113861084秒。
接下来我们采用常规做法:
conn = pymysql.connect(host=‘127.0.0.1‘,user=‘root‘,password=‘root‘,database=‘python_scrapy‘,charset=‘utf8‘) cursor = conn.cursor() start_time=time.time() for i in range(1,10001): sql = ‘insert into btree(sid,name,email) values(%s,%s,concat(%s,"hael","@163"));‘ res = cursor.execute(sql,[i,"root",i]) conn.commit() cursor.close() conn.close() stop_time=time.time() print(‘run time is %s‘ %(stop_time-start_time)) #output : run time is 3.1362051963806152
可以看到实现相同的功能我们用了
3.1362051963806152秒。
原文:https://www.cnblogs.com/wujf-myblog/p/12340713.html