geekdoc-python-zh/docs/pythonland/51.md

65 lines
2.8 KiB
Markdown

# 设定基线
> 原文:[https://python.land/python-concurrency/setting-the-baseline](https://python.land/python-concurrency/setting-the-baseline)
在所有关于 [Python 并发](https://python.land/python-concurrency)和 [Python GIL](https://python.land/python-concurrency/the-python-gil) 的理论之后,我们现在准备好一些示例代码和实验。我们开始工作吧!
目录
* [我们的测试函数](#Our_test_function "Our test function")
* [基线:单线程执行](#The_baseline_single_threaded_execution "The baseline: single threaded execution")
## 我们的测试函数
让我们首先定义一个函数,我们可以用它来测试我们不同的选项。以下所有示例都使用相同的函数,称为 *heavy* :
```py
def heavy(n, myid):
for x in range(1, n):
for y in range(1, n):
x**y
print(myid, "is done")
```
*heavy* 函数是一个嵌套的 [Python for 循环](https://python.land/introduction-to-python/python-for-loop),它执行乘法运算。这是一个受 CPU 限制的函数。如果您在运行时观察您的系统,您将看到 CPU 使用率接近 100%(对于一个内核)。你可以用你想要的任何东西来代替它,但是要注意竞争条件——不要使用共享对象或变量。
我们将以不同的方式运行这个函数,并探索常规单线程 Python 程序、多线程和多重处理之间的差异。
Thank you for reading my tutorials. I write these in my free time, and it requires a lot of time and effort. I use ads to keep writing these *free* articles, I hope you understand! **Support me by disabling your adblocker on my website** or, alternatively, **[buy me some coffee](https://www.buymeacoffee.com/pythonland)**. It's much appreciated and allows me to keep working on this site!
## 基线:单线程执行
每个 Python 程序至少有一个线程:主线程。下面你会发现单线程版本,这是我们的速度基准。它按顺序运行我们的繁重函数 80 次:
```py
import time
# A CPU heavy calculation, just
# as an example. This can be
# anything you like
def heavy(n, myid):
for x in range(1, n):
for y in range(1, n):
x**y
print(myid, "is done")
def sequential(n):
for i in range(n):
heavy(500, i)
if __name__ == "__main__":
start = time.time()
sequential(80)
end = time.time()
print("Took: ", end - start)
```
在我的系统上,这大约需要 46 秒才能完成。
请注意,`if __name__ == "__main__":`部分是在 Windows 计算机上工作所必需的,但最好总是使用它。
在接下来的文章中,我们将探索一个[线程版本](https://python.land/python-concurrency/python-threads)和一个[多处理版本](https://python.land/python-concurrency/python-multiprocessing),并了解这两种编写并发代码方式的区别。