Skip to content

Instantly share code, notes, and snippets.

@danielecook
Forked from juancarlospaco/0README.md
Created November 14, 2019 10:02
Show Gist options
  • Save danielecook/c88bd8342a7f12d339304eb13094fd55 to your computer and use it in GitHub Desktop.
Save danielecook/c88bd8342a7f12d339304eb13094fd55 to your computer and use it in GitHub Desktop.
Python Versus Nim: Async

Python Versus Nim: Async

  • No performance benchmark.
  • Python ⟿ PEP-8
  • Nim ⟿ NEP1
  • Python ⟿ 3.7
  • Nim ⟿ 0.19
  • No Ofuscation, no Code-Golf.

This is to compare elegant, simple, expressive code. :cat:

import asyncdispatch
proc helloWorld() {.async.} =
echo "Hello World"
wait_for helloWorld()
import asyncio
async def async_function():
print("Hello World")
asyncio.run(async_function())
import asyncdispatch, os
type SomeObject = object
limit: int
iterator items(self: SomeObject): int =
for i in 0..self.limit:
sleep 1_000
yield i
proc asyncFunction() {.async.} =
for i in SomeObject(limit: 9):
echo i
wait_for asyncFunction()
import asyncio
class SomeObject(object):
def __init__(self, limit):
self.limit = limit
def __aiter__(self):
return self
async def __anext__(self):
if not self.limit:
raise StopAsyncIteration
self.limit -= 1
await asyncio.sleep(1)
return self.limit
async def async_function():
async for date in SomeObject(9):
print(date)
asyncio.run(async_function())
import asyncdispatch, threadpool
proc threadedFunction(i: int) {.async.} =
echo i
proc asyncFunction() {.async.} =
for i in 0..9:
discard spawn: threadedFunction(i)
wait_for asyncFunction()
import asyncio
def threaded_function(i):
print(i)
async def async_function():
for i in range(9):
await loop.run_in_executor(None, threaded_function, i)
loop = asyncio.get_event_loop()
loop.run_until_complete(async_function())
import asyncdispatch
proc asyncFunction(counter = 9) {.async, discardable.} =
echo counter
var count = counter
dec count
if count > 0:
discard sleepAsync(1_000)
asyncFunction(count)
wait_for asyncFunction()
import asyncio
def async_function(counter=9):
print(counter)
counter -= 1
if counter:
loop.call_later(1, async_function, counter)
else:
loop.stop()
loop = asyncio.get_event_loop()
loop.call_soon(async_function)
loop.run_forever()
import asyncdispatch
proc asyncFunction() {.async.} =
var remaining = 9
while true:
echo remaining
dec remaining
if not (remaining > 0):
break
await sleepAsync(1_000)
wait_for asyncFunction()
import asyncio
async def async_function():
remaining = 9
while True:
print(remaining)
remaining -= 1
if not remaining:
break
await asyncio.sleep(1)
asyncio.run(async_function())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment