Skip to content

Instantly share code, notes, and snippets.

@sourabh2k15
Last active December 17, 2017 04:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sourabh2k15/d0135642b089ec6a2ea978d6cd3b30fa to your computer and use it in GitHub Desktop.
Save sourabh2k15/d0135642b089ec6a2ea978d6cd3b30fa to your computer and use it in GitHub Desktop.
defmodule Async do
@n_clients 100000
def createFollowersSync(n_clients) do
Enum.reduce(1..n_clients, [], fn rank, acc ->
acc ++ [Util.pickRandom(@n_clients, rank)]
end)
end
def createFollowersAsync(n_clients) do
chunks = Enum.chunk_every(1..n_clients, 1000)
chunked_tasks = Enum.map(chunks, fn chunk ->
Task.async(fn ->
Enum.reduce(chunk, [], fn x, acc ->
acc ++ [Util.pickRandom(@n_clients, x)]
end)
end)
end)
Enum.reduce(chunked_tasks, [], fn chunk_task, acc ->
acc ++ Task.await(chunk_task)
end)
end
def start do
start_time = :os.system_time(:milli_seconds)
followers = createFollowersAsync(@n_clients)
end_time_1 = :os.system_time(:milli_seconds)
IO.inspect followers
IO.puts length(followers)
IO.puts "took #{(end_time_1 - start_time)}"
end
end
@sourabh2k15
Copy link
Author

util module :

defmodule Util do
    # Utility functions 

    # picks a random node from a given list
    def pickRandom(max, current) do
        num = rand(1, max)
        
        if num != current do 
            num 
        else 
            pickRandom(max, current) 
        end
    end
    
    # generates random number in range 
    def rand(r_min, r_max) do
        rand_int = :rand.uniform()*(r_max - r_min + 1) |> :math.floor |> Kernel.+(r_min) |> round

        if rand_int != nil do 
            rand_int
        else
            rand(r_min, r_max)
        end
    end

    def log2(n) do
        :math.log(n) / :math.log(2) |> round
    end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment