Skip to content

Instantly share code, notes, and snippets.

@schinsue
Created March 19, 2024 19:28
Show Gist options
  • Save schinsue/469d1e3c259d15ffdd766aa301c93383 to your computer and use it in GitHub Desktop.
Save schinsue/469d1e3c259d15ffdd766aa301c93383 to your computer and use it in GitHub Desktop.
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