Skip to content

Instantly share code, notes, and snippets.

@akira345
Last active August 3, 2016 11:43
Show Gist options
  • Save akira345/6325783c0cc3f894d845810bb695afd5 to your computer and use it in GitHub Desktop.
Save akira345/6325783c0cc3f894d845810bb695afd5 to your computer and use it in GitHub Desktop.
Rubyで重い処理を並列動作させるサンプルスクリプトです。
# -*- coding: utf-8 -*-
#
# Rubyで重い処理を並列動作させるサンプルスクリプトです。
require 'parallel'
require 'pp'
# 開始時刻と終了時刻を記録するクラス
class RecordUtil
#クラス変数を使用してインスタンス間で共通変数を参照する。
@@record_table = []
@@mutex = Mutex.new
#クラス変数にはattr_accessが使えないので自前でアクセッサを用意
def record_table
@@record_table
end
#レコード記録
def write_record(key,start_time,end_time)
@@mutex.synchronize do
tmp = {}
tmp = { key: key, start_time: start_time, end_time: end_time }
@@record_table.push tmp
end
end
end
# 開始時刻と終了時刻を記録する
# 重い関数たち
def heavy_function
pp "START heavy function"
key = "heavy function"
start_time = Time.now
sleep(5)
end_time = Time.now
pp "END heavy function"
#時刻を記録
util = RecordUtil.new
util.write_record(key,start_time,end_time)
end
def slow_function
pp "START slow function"
key = "slow_function"
start_time = Time.now
sleep(1)
pp "END slow function"
end_time = Time.now
#時刻を記録
util = RecordUtil.new
util.write_record(key,start_time,end_time)
end
# 並列実行したい関数を登録
functions = []
functions.push Proc.new {
heavy_function()
}
functions.push Proc.new {
slow_function()
}
pp "並列処理開始"
Parallel.each(functions,in_threads:2) do | block |
block.call
end
# 結果を表示
util = RecordUtil.new
pp util.record_table
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment