![715005580f9af67d3630dab10bf4f509.png](https://img-blog.csdnimg.cn/img_convert/715005580f9af67d3630dab10bf4f509.png)
小编在前两天开通了一个 Python 金融的专栏,顺便用 TuShare 下载了几只 A股的数据,有兴趣的小伙伴可以去看一下:
多多教Python:Python 金融: TuShare API 获取股票数据 (1)zhuanlan.zhihu.com![c076b6c37436004e9f9e8859974ab6f9.png](https://img-blog.csdnimg.cn/img_convert/c076b6c37436004e9f9e8859974ab6f9.png)
大概下载了十几只股票,然后在接下来的教程中做数据清洗和整理。但是一只一只股票按顺序做下来速度会很慢,所以在这之前我们先来讲一下如何在 Python 做多线程运算,来帮助我们提高多任务处理的速度。
这篇教程讲建立在之前两篇的基础之上,所以有兴趣的小伙伴可以去阅读一下:
多多教Python:Python 基本功: 6. 第一个完整的程序zhuanlan.zhihu.com![f1ce30863d64a852a665c0176a2c0310.png](https://img-blog.csdnimg.cn/img_convert/f1ce30863d64a852a665c0176a2c0310.png)
![dbe96809aed9e504c7632ffbac16ce10.png](https://img-blog.csdnimg.cn/img_convert/dbe96809aed9e504c7632ffbac16ce10.png)
教程需求:
- Mac OS (Windows, Linux 会略有不同)
- 安装了 Python 3.0 版本以上, PyCharm, Microsoft Office Excel
- 阅读了 多多教Python:Python 基本功: 6. 第一个完整的程序,多多教Python:Python 基本功: 10. 面对对象-类 Class。
多线程 Multi-Threading
多线程是指在一个进程中,允许几段代码并发式的同时运行。Python 的多线程运算就是利用了这一点,可以让代码的运行方法更加丰富有效。这里需要用到的一个库叫 Threading,这个库可以直接调用其中的函数,或者通过继承类来实现,下面我们来分别通过这两个方法来对运算进行提速。
- 函数多线程
import threading
def func(times, name, ret):
for i in range(times):
print(name + ' run: ' + str(i))
ret[name] = name + " finished with " + str(times) + " times printed"
return
if __name__ == '__main__':
thread_pool = []
ret = {}
th_1 = threading.Thread(target=func, args=[3, 'th_1', ret], name='th_1')
th_2 = threading.Thread(target=func, args=[5, 'th_2', ret], name='th_2')
thread_pool.append(th_1)
thread_pool.append(th_2)
for th in thread_pool:
th.start()
for th in