Created
March 19, 2024 19:28
-
-
Save schinsue/469d1e3c259d15ffdd766aa301c93383 to your computer and use it in GitHub Desktop.
This file contains 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
defmodule BeExercise.DatabaseSeeder do | |
alias BeExercise.Repo | |
alias BeExercise.Accounts | |
alias BeExercise.Accounts.User | |
alias BeExercise.Finances | |
alias Faker.{Person, Internet} | |
alias Ecto.Multi | |
@currencies Finances.get_current_known_currencies() | |
def insert_user do | |
generate_user() | |
|> Accounts.create_user() | |
end | |
def drop do | |
Repo.delete_all(User) | |
end | |
def insert_user_multi() do | |
Multi.new() | |
|> Multi.insert(:user, User.changeset(%User{}, generate_user())) | |
|> Repo.transaction() | |
end | |
defp generate_user() do | |
%{ | |
name: Person.first_name(), | |
email: Internet.email(), | |
salaries: [generate_salary(), generate_salary(true)] |> Enum.shuffle() | |
} | |
end | |
defp generate_salary(random_active \\ false) do | |
active = if random_active, do: Enum.random([true, false]), else: false | |
%{ | |
currency: Enum.random(@currencies), | |
amount: Enum.random(0..300_000) |> Decimal.new(), | |
active: active | |
} | |
end | |
end | |
BeExercise.DatabaseSeeder.drop() | |
Benchee.run(%{ | |
"original" => fn -> | |
1..100_000 | |
|> Enum.each(fn _ -> | |
BeExercise.DatabaseSeeder.insert_user() | |
end) | |
end, | |
"improved.task_async_stream" => fn -> | |
1..100_000 | |
|> Task.async_stream(fn _ -> | |
BeExercise.DatabaseSeeder.insert_user() | |
end) | |
|> Stream.run() | |
end, | |
"improved.task_async_stream_multi" => fn -> | |
1..100_000 | |
|> Task.async_stream(fn _ -> | |
BeExercise.DatabaseSeeder.insert_user_multi() | |
end) | |
|> Stream.run() | |
end | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment