协程如何提高性能

发布于 2024-11-18 10:28:15 字数 173 浏览 2 评论 0 原文

我看过很多关于 python 协程的演讲和文章。它们被认为是“微线程”,我听说它们可以提高性能。

协程如何提高性能?从我到目前为止所看到的来看,它们是单线程的并且按顺序执行。我同意,从设计的角度来看,它们非常优雅,尤其是在生产者/消费者类型的应用程序中。

我想我没有抓住重点。有人可以帮忙解释一下吗?

I've been seeing a lot of talks and articles on coroutines in python. They are considered to be "microthreads" and I've heard they improve performance.

How do coroutines improve performance? From what I've seen so far, they are single threaded and execute in sequence. I agree that from a design perspective they are quite elegant especially in producer/consumer type applications.

I guess I am missing the point. Can someone help explain?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

丶情人眼里出诗心の 2024-11-25 10:28:15

协程并不会真正提高性能,除非在非常有限的意义上:多线程程序有一定的开销,而协程提供了线程的一些好处,而不会产生这些开销。然而,当一个线程在系统调用上阻塞而其他线程可以运行时,大多数多线程应用程序(甚至在具有 GIL 的 C-Python 中)都会受益于重叠:这通常不会发生在协程中。

如果您有几个线程,那么通常重叠会胜出,并且协程不会带来任何性能优势。如果您需要数千个线程,那么线程切换开销将会更大,在这种情况下,协程可能会带来好处,但减少线程数量可能会带来更大的好处。

协程的真正好处在于,对于生产者/消费者应用程序来说,它们使编码变得更加简单,因此编码速度更快。

Coroutines don't really improve performance except in a very limited sense: multi-threaded programs have a certain overhead and coroutines provide some of the benefit of threading without incurring those overheads. However, most multi-threaded applications (even in C-Python with its GIL) benefit from the overlap when one thread blocks on a system call and other threads can run: that doesn't generally happen with coroutines.

If you have a few threads then usually the overlapping wins out and coroutines give no performance benefit. If you need thousands of threads then the thread switch overheads will be much greater and in that situation coroutines might give a benefit but reducing the number of threads is likely to give much greater benefit.

The real gain of coroutines is that for producer/consumer applications they make the coding much simpler and therefore faster to code.

指尖上得阳光 2024-11-25 10:28:15

这是一个很好的问题,它让我想起了 David Beazley 的 关于协程和并发的有趣课程。 David 做得非常出色,不仅解释了协程在 Python 中的工作原理,还解释了它们真正有用的用例。

他的文章似乎表明,性能优势来自于以更少的开销来完成通常使用处理程序类完成的相同任务(请参见 他的演示文稿)。

因此,就像 @Duncan 的回答 所建议的那样,在开销很重要的情况下(比如有很多线程),协程是性能上的胜利,但协程的意义远不止于性能。

This is a good question, it reminded me of David Beazley's A Curious Course on Coroutines and Concurrency. David does an excellent job of not only explaining how coroutines work in Python, but the use cases where they're really in the pocket.

His writing seems to indicate that the performance benefit comes from having less overhead to accomplish the same tasks for which you'd typically use a handler class (see slide 51 of his presentation).

So like @Duncan's answer suggests, situations where overhead matters (like having many many threads), coroutines are a performance win, but coroutines are about a lot more than just performance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文