tasyncall.nim 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. discard """
  2. exitcode: 0
  3. """
  4. import times, sequtils
  5. import asyncdispatch
  6. const
  7. taskCount = 10
  8. sleepDuration = 50
  9. proc futureWithValue(x: int): Future[int] {.async.} =
  10. await sleepAsync(sleepDuration)
  11. return x
  12. proc futureWithoutValue() {.async.} =
  13. await sleepAsync(sleepDuration)
  14. proc testFuturesWithValue(x: int): seq[int] =
  15. var tasks = newSeq[Future[int]](taskCount)
  16. for i in 0..<taskCount:
  17. tasks[i] = futureWithValue(x)
  18. result = waitFor all(tasks)
  19. proc testFuturesWithoutValues() =
  20. var tasks = newSeq[Future[void]](taskCount)
  21. for i in 0..<taskCount:
  22. tasks[i] = futureWithoutValue()
  23. waitFor all(tasks)
  24. proc testVarargs(x, y, z: int): seq[int] =
  25. let
  26. a = futureWithValue(x)
  27. b = futureWithValue(y)
  28. c = futureWithValue(z)
  29. result = waitFor all(a, b, c)
  30. proc testWithDupes() =
  31. var
  32. tasks = newSeq[Future[void]](taskCount)
  33. fut = futureWithoutValue()
  34. for i in 0..<taskCount:
  35. tasks[i] = fut
  36. waitFor all(tasks)
  37. block:
  38. let
  39. startTime = cpuTime()
  40. results = testFuturesWithValue(42)
  41. expected = repeat(42, taskCount)
  42. execTime = cpuTime() - startTime
  43. doAssert execTime * 1000 < taskCount * sleepDuration
  44. doAssert results == expected
  45. block:
  46. let startTime = cpuTime()
  47. testFuturesWithoutValues()
  48. let execTime = cpuTime() - startTime
  49. doAssert execTime * 1000 < taskCount * sleepDuration
  50. block:
  51. let startTime = cpuTime()
  52. testWithDupes()
  53. let execTime = cpuTime() - startTime
  54. doAssert execTime * 1000 < taskCount * sleepDuration
  55. block:
  56. let
  57. startTime = cpuTime()
  58. results = testVarargs(1, 2, 3)
  59. expected = @[1, 2, 3]
  60. execTime = cpuTime() - startTime
  61. doAssert execTime * 100 < taskCount * sleepDuration
  62. doAssert results == expected
  63. block:
  64. let
  65. noIntFuturesFut = all(newSeq[Future[int]]())
  66. noVoidFuturesFut = all(newSeq[Future[void]]())
  67. doAssert noIntFuturesFut.finished and not noIntFuturesFut.failed
  68. doAssert noVoidFuturesFut.finished and not noVoidFuturesFut.failed
  69. doAssert noIntFuturesFut.read() == @[]