Guest User

Untitled

a guest
Mar 23rd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2.  
  3. require 'benchmark'
  4.  
  5. # global executorの並列度を高めにしてから...
  6. def concurrent_download(files, future_provider: Concurrent::Future)
  7. require 'concurrent/future'
  8.  
  9. # 最大20ファイルずつ並列ダウンロード
  10. n = 20
  11.  
  12. download_sets = files.each_slice(n).map { |fs|
  13. fs.map { |f| future_provider.execute { sleep(rand); puts "Downloading #{f}"; f } }
  14. }
  15.  
  16. downloaded_files = future_provider.execute {
  17. download_sets.inject([]) { |completed, ds|
  18. ds.each { |d|
  19. completed << d.value
  20. }
  21. completed
  22. }
  23. }.value
  24. end
  25.  
  26. class Task
  27. attr_accessor :thread, :result
  28.  
  29. def self.execute(&block)
  30. task = Task.new
  31. t = Thread.start(task, block) do |t, b|
  32. t.result = b.call
  33. end
  34. task.thread = t
  35. end
  36.  
  37. def value
  38. thread.join
  39. result
  40. end
  41. end
  42.  
  43. Benchmark.bm do |x|
  44. x.report do
  45. files = 1.upto(30).map { |num| "file#{num}" }
  46. r = concurrent_download(files, future_provider: Task)
  47. puts "Completed downloading #{files.count} files: #{r}"
  48. end
  49. end
Add Comment
Please, Sign In to add comment