Another example of sequential and synchronous execution of tasks in a loop. In this example too we'll use `sleep` to pretend we are waiting for some external task to finish, but this time we'll start a number of jobs based on what the user supplies. We can't know up-front how many tasks we'll have to call. Output Start 0 End 0 Start 1 End 1 Start 2 End 2 Start 3 End 3 Elapsed 4.004362344741821 As one could expect from such code, the total time required for such program to run is the sum of all the tasks as they run sequentially. Source: https://lnkd.in/dm9GBJXd Author: Gábor Szabó
About us
Python Maven is for people who are interested in Python tips, ideas and tutorials.
- Website
-
https://python.code-maven.com/
External link for Python Maven
- Industry
- Software Development
- Company size
- 1 employee
- Headquarters
- Modiin
- Specialties
- Python
Updates
-
Plain printing example with async #Python * This is almost the same example as we had previously, but we wait asynchronously. * The order of the output is now different. * It also finishes 1 sec faster. It finishes when the longest wait ends. What did we don? * We added async in-front of the function definitions to make them co-routines. * We replaced the time.sleep by asyncio.sleep that can handle async sleep. * We called this new sleep function with the await keyword. That tells the even-loop that other tasks can run till this thing we are awaiting-for finishes. * We called the say function inside an await-ed call to asyncio.gather. * We started the event loop with asyncio.run. Output <coroutine object main at 0x78265ad9a4d0> start main Second First Elapsed: 2.0022734529920854 The first print shows that what the main function returns is a object of type coroutine. The "Second" print appears before the "First", because the former only had to wait 1 second why the latter waited 2 seconds. source: https://lnkd.in/dhqq35jN Author: Gábor Szabó
-
-
Before getting into async in #Python this is a simple example of printing in sync. * In this example we use sleep to imitate some external task we need to wait for and then we print out some text. * We do it sequentially. No async here. The output is First Second Elapsed: 3.0015416080132127 So it takes slightly more than 3 seconds to wait first for 2 and then for 1 second. No big surprise there. Source: https://lnkd.in/dXZiwSt6 Author: Gábor Szabó
-
-
#Async programming in #Python I have been writing about Async programming in #Rust and I figured I should start publishing here again about Python. What could be a better idea that to start publishing the pages from the Async programming in Python book I am writing. Here is the link to where you can find the most recent version of the whole book: https://lnkd.in/dXZiwSt6 Enjoy and let me (Gábor Szabó) know what you think.