Last active
May 31, 2017 03:13
-
-
Save ShadowfeindX/1afc3e6d9190c98c06fe8218365896af to your computer and use it in GitHub Desktop.
Integer Pow function and Benchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Following Zen | |
defmodule Math do | |
def pow(0,_), do: 0 | |
def pow(_,0), do: 1 | |
def pow(lhs,rhs) when rhs < 0, do: 1 / pow(lhs,-rhs) | |
def pow(lhs,rhs), do: 1..rh |> Enum.reduce(1, &(elem({&1, &2*lhs},1))) | |
end | |
defmodule Benchmark do | |
def time(m,f,a) do | |
timer = fn _, x -> | |
{time, _result} = :timer.tc(m,f,a) | |
x + time | |
end | |
1..1_000 | |
|> Enum.reduce(timer) | |
|> div(1_000) | |
end | |
end | |
Benchmark.time(Math, :pow, [123, 123]) | |
|> IO.inspect |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Being Me | |
defmodule Math, do: (def pow(0,_), do: 0; def pow(_,0), do: 1; def pow(lhs,rhs) when rhs < 0, do: 1 / pow(lhs,-rhs); def pow(lhs,rhs), do: Enum.reduce(1..rh, 1, &(elem({&1, &2*lhs},1))) | |
defmodule Benchmark, do: (def time(m,f,a), do: div(Enum.reduce(1..1_1000, &(&2 + elem({&1, _} = :timer.tc(m,f,a), 0))), 1_000)) | |
IO.inspect(Benchmark.time(Math, :pow, [123, 123])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment