标签:朋友 imp [] nbsp thread 命令行启动 threading eve name
因为一个朋友最近想搞接口压力测试,推荐了jmeter,因为jmeter开源,且有命令行启动模式,方便封装。兴起时,自己也简单实现了一下高并发的脚本。
采用的是多进程+多线程+协程。想法是这样的,多进程是为了有效利用多核,理论上最好一个核对应一个进程比较好;那我为什么还要用多线程呢?不怕GIL全局锁吗?这是因为我用了gevent处理,请求采用requests,但requests是阻塞的方法,所以我把requests操作丢到协程做,就没啥问题了。接下来看看脚本,实现了一个2000并发量的脚本(写的比较烂,不要在意这些细节)
# coding:utf-8 import multiprocessing import requests import threading import gevent process_num = 10 # 进程数 gevent_num = 10 # 协程数 threading_num = 20 def asynchronous(url): threads = [] for i in range(gevent_num): threads.append(gevent.spawn(request_url, url)) gevent.joinall(threads) def request_url(url): code = requests.get(url).status_code if code != 200: print "the time request failed: " + str(code) else: print "the time request ok" def run_in_thread(url): threadings = [] for i in xrange(threading_num): t = threading.Thread(target=asynchronous, args=(url,)) t.daemon = True t.start() threadings.append(t) for t in threadings: t.join() if __name__ == ‘__main__‘: pool = multiprocessing.Pool(processes=process_num) for i in range(process_num): pool.apply_async(run_in_thread, ("https://www.baidu.com",)) pool.close() pool.join()
标签:朋友 imp [] nbsp thread 命令行启动 threading eve name
原文地址:http://www.cnblogs.com/alexkn/p/7059832.html