1

I’ve got a burning question. Recently I’ve been learning Asyncio in Python and found it very useful and efficient but here is my question: is it efficient to use it for “normal” things?

It’s obvious that using asynchronous operations for making requests, handling requests (in apis), working on files will give us performance gain. But how I put other operations? For example, if I want to do a lot of complicated mathematical operations or just standard operations (without files and web), would asyncio help me anyway? Is there any reason why we should use it outside our apps where we are not making requests and doing all this web or files stuff?

I’m wondering because in college teachers never mentioned that we couldn’t get any better by using it for just math or standard (local?, non-file, non-web) operations and I thought that we benefit from it (almost always). Am I totally wrong? Is it that way just in python or in every other language ?

  • No, as the name implies it's only good for I/O bound operations, that is, when you make a call that you have to wait for a response from. Number crunching won't benefit from it so you'll want to consider multiprocessing if libraries like numpy are still not fast enough for you. – new-dev-123 Aug 22 '19 at 05:52

1 Answers1

0

asyncio in the first place is a convenient way to run multiple execution flows (compared to common alternatives like callbacks and threads).

Why would someone want to run multiple execution flows? Usually to gain performance, for example:

  • You don't want to waste time waiting one network request finished, so you starting another concurrently gaining performance
  • You don't want to waste time waiting one OS thread finished, so you starting another concurrently. In Python due to GIL you won't gain performance with threads for CPU-bound operations. But they can still be useful for network stuff or specifically in asyncio as a common way to run something blocking without freezing event loop.
  • You don't want to waste time waiting one OS process finished, so you starting another concurrently.

Last item is a way to gain performance even for purely CPU-bound operations (if machine have multiple cores). You can see example here (third option). asyncio here, again, is just a tool for convenient managing execution flows. Nothing stops you from using pure ProcessPoolExecutor and de-facto callbacks as shown here.

Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159