tparfind.nim 711 B

123456789101112131415161718192021222324252627282930
  1. discard """
  2. matrix: "--mm:refc"
  3. output: "500"
  4. """
  5. import threadpool, sequtils
  6. {.experimental: "parallel".}
  7. proc linearFind(a: openArray[int]; x, offset: int): int =
  8. for i, y in a:
  9. if y == x: return i+offset
  10. result = -1
  11. proc parFind(a: seq[int]; x: int): int =
  12. var results: array[4, int]
  13. parallel:
  14. if a.len >= 4:
  15. let chunk = a.len div 4
  16. results[0] = spawn linearFind(a[0 ..< chunk], x, 0)
  17. results[1] = spawn linearFind(a[chunk ..< chunk*2], x, chunk)
  18. results[2] = spawn linearFind(a[chunk*2 ..< chunk*3], x, chunk*2)
  19. results[3] = spawn linearFind(a[chunk*3 ..< a.len], x, chunk*3)
  20. result = max(results)
  21. let data = toSeq(0..1000)
  22. echo parFind(data, 500)