1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

概要

paiza.ioでelixirやってみた。
Scheduler使ってみた。

サンプルコード


defmodule FibSolver do
	def fib(scheduler) do
		send scheduler, {:ready, self()}
		receive do
			{:fib, n, client} ->
				send client, {:answer, n, fib_calc(n), self()}
				fib(scheduler)
			{:shutdown} ->
				exit(0)
		end
	end
	defp fib_calc(0), do: 1
	defp fib_calc(1), do: 1
	defp fib_calc(n), do: fib_calc(n - 1) + fib_calc(n - 2)
end

defmodule Scheduler do
	def run(num_processes, module, func, to_calculate) do
		(1..num_processes)
		|> Enum.map(fn(_) ->
			spawn(module, func, [self()])
		end)
		|> schedule_processes(to_calculate, [])
	end
	defp schedule_processes(processes, queue, results) do
		receive do
			{:ready, pid} when length(queue) > 0 ->
				[next | tail] = queue
				send pid, {:fib, next, self()}
				schedule_processes(processes, tail, results)
			{:ready, pid} ->
				send pid, {:shutdown}
				if length(processes) > 1 do
					schedule_processes(List.delete(processes, pid), queue, results)
				else
					Enum.sort(results, fn {n1, _}, {n2, _} ->
						n1 <= n2
					end)
				end
			{:answer, number, result, _pid} ->
				schedule_processes(processes, queue, [{number, result} | results])
		end
	end
end

to_process = [27, 32, 12, 26, 24, 10, 9, 8, 7, 6, 5, 17, 30, 11, 13]
Enum.each 1..7, fn num_processes ->
	{time, result} = :timer.tc(Scheduler, :run, [num_processes, FibSolver, :fib, to_process])
	if num_processes == 1 do
		IO.puts inspect result
		IO.puts "no   time(ms)"
	end
	:io.format "~2B   ~.1f~n", [num_processes, time / 1000.0]
end



実行結果

[{5, 8}, {6, 13}, {7, 21}, {8, 34}, {9, 55}, {10, 89}, {11, 144}, {12, 233}, {13, 377}, {17, 2584}, {24, 75025}, {26, 196418}, {27, 317811}, {30, 1346269}, {32, 3524578}]
no   time(ms)
 1   104.6
 2   99.1
 3   99.7
 4   99.0
 5   100.0
 6   101.0
 7   99.1

成果物

以上。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?