oegma2

oegma2

Hi, I am new to Elixir world and still have a long way to go, but starting with a basic problem I’ve been using to learn any new language - one with monkies hitting random keys and see if they can write a chapter out of Shakespeare’s book :slight_smile: - but in order to solve this problem, I need to generate a random letter, representing the monkey’s hitting a key…So after a bit of googling found an option using List and rand.uniform(…) to return a random “key” out of a fixed list

The problem is, doing this function over and over is a key component and is really slow compared to any other language… I know Elixir and the BEAM VM are designed for reliability and thus immutable obj can slow things down…

Is there any solution to speed this code up below, so that I can continue the journey with Elixir and write a program that can spawn million’s of monkies, all hitting keys

chars = ‘ABCDEFGHIJKLMNOPQRSTUVW’
data = List.to_tuple(chars)

for x ← 0..1000000 do
elem(data, :rand.uniform(22))
end

Showing Posts 1 to 9

hauleth

hauleth

Lists do not support random access and access is linear, so to get nth element you need n steps. In other words the Enum.at/2 for list will be implemented as:

def at([], _), do: nil
def at([val | rest], 0), do: val
def at([_ | rest], n) when n > 0, do: at(rest, n - 1)
oegma2

oegma2 OP

Thanks for the help, and learned very quickly that in func lang, recursive is your friend :slight_smile: - meaning you can’t do list[index] … that not gone work

I tried your solution above but seems slower (And tried as in I prbl done something horribly wrong using your code, but have to start somewhere :)) - used Benchee for my benchmark results

defmodule Monkeyatwork do
  def at([], _), do: nil
  def at([val | rest], 0), do: val
  def at([_ | rest], n) when n > 0, do: at(rest, n - 1)     

  def test1() do
    chars = 'ABCDEFGHIJKLMNOPQRSTUVW'
    data = List.to_tuple(chars)
    
    for x <- 0..1000000 do 
        elem(data, :rand.uniform(22))    
    end        
  end

  def test2() do
    chars = 'ABCDEFGHIJKLMNOPQRSTUVW'
    
    for x <- 0..1000000 do 
      at(chars, :rand.uniform(22))    
    end        
  end  
end

Benchee.run(
  %{
    "test1" => fn -> Monkeyatwork.test1() end,
    "test2" => fn -> Monkeyatwork.test2() end
  }
)

My results

Benchmarking test1...
Benchmarking test2...

Name            ips        average  deviation         median         99th %
test1          2.39      419.25 ms     ┬▒4.15%      414.50 ms      453.00 ms
test2          1.89      528.10 ms     ┬▒3.04%      523.50 ms      562.00 ms

Comparison:
test1          2.39
test2          1.89 - 1.26x slower +108.85 ms
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

He wasn’t providing a faster solution, he was showing how the code underlying your existing solution worked, demonstrating that it was O(N).

Probably the fastest thing is to just compute a random number between 0 and 22 and add the correct ASCII offset.

random_char = [:random.uniform(22) + 65]
hauleth

hauleth

Except I would write it as:

random_char = [:rand.uniform(?Z - ?A) + ?A)]

For less “magic numbers”. Also :rand is preferred solution over :random.

However I am not sure if Enum.random(?A..?Z) isn’t optimised for such case (and if not it probably would be nice addition).

EDIT:

Enum.random(?A..?Z) will run in constant time and space, so it would be the best and the fastest solution.

cc @oegma2

oegma2

oegma2 OP

Thanks, @hauleth, and @benwilson512 for the input - going to try the Enum.random(?A..?Z), [:rand.uniform(?Z - ?A) + ?A)] and [:rand.uniform(?Z - ?A) + ?A)]

Agree with @hauleth regarding the :rand is preferred solution over :random - valid point, but my use-case, don;t need true crypto style random numbers. But good to keep it in mind

Thanks so much for the help and quick response - really awesome community!

hauleth

hauleth

For cryptographically secure rands you need to use :crypto.random_bytes/1, :rand isn’t crypto safe either.

rvirding

rvirding

Creator of Erlang

Yes, this is explicitly mentioned in the module rand docs:

The builtin random number generator algorithms are not cryptographically strong. If a cryptographically strong random number generator is needed, use something like crypto:rand_seed/0.

oegma2

oegma2 OP

So I’ve done some testing and found 2 options that pretty fast for our Monkey app hitting random keys. Thanks to @hauleth and @benwilson512 for providing me with test1 option below

@hauleth / @rvirding : Thanks for the info on :rand regarding crypto. For my example, since the monkies just need a random number, it don’t need super secure random numbers, just random. But solid info and will keep that in mind for future projects that require secure random numbers.

Back to the monkies app - The strange part is that using tuple’s in this case with the Kernel elem(tuple, index) seems to be a bit faster than Enum.random(?A..?Z)

I’ve asked the Monkies to try and type the following sequence in order “FOXYL” at random, and if they type FOD they start over - must be in perfect sequence, else they start from scratch. It’s actually scary to think a random monkey got that word in under 4 seconds in test1 and under 2 seconds in test2 :slight_smile:

Below is the results from Benchee
test1 using Enum.random(?A..?Z)
test2 using

  def rand_key() do
    data = {65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90}
    elem(data, :rand.uniform(26) - 1)    
  end
Name            ips        average  deviation         median         99th %
test2          0.62         1.62 s    ┬▒82.72%         1.44 s         3.87 s
test1          0.22         4.49 s    ┬▒87.21%         3.42 s         8.83 s

Comparison:
test2          0.62
test1          0.22 - 2.76x slower +2.86 s
hauleth

hauleth

Ok, I have tested on my own, and to my surprise you are right.

range = ?A..?Z
tuple = range |> Enum.to_list() |> List.to_tuple()

defmodule Bench.Random do
  def pick(from..to), do: from + :rand.uniform(to - from)
end

Benchee.run(
  %{
    "tuple" => fn -> for _ <- 0..1000, do: elem(tuple, :rand.uniform(tuple_size(tuple)) - 1) end,
    "range" => fn -> for _ <- 0..1000, do: Enum.random(range) end,
    "picker" => fn -> for _ <- 0..1000, do: Bench.Random.pick(range) end,
    "add random" => fn -> for _ <- 0..1000, do: ?A + :rand.uniform(tuple_size(tuple)) end
  }
)

Results with:

Operating System: macOS"
CPU Information: Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
Number of Available Cores: 12
Available memory: 32 GB
Elixir 1.9.4
Erlang 22.1.7

Benchmark suite executing with the following configuration:
warmup: 2 s
time: 5 s
memory time: 0 μs
parallel: 1
inputs: none specified
Estimated total run time: 28 s


Benchmarking add random...
Benchmarking picker...
Benchmarking range...
Benchmarking tuple...

Name                 ips        average  deviation         median         99th %
add random        5.26 K      190.09 μs     ±9.44%         184 μs         276 μs
tuple             5.21 K      191.99 μs     ±7.48%         189 μs         272 μs
picker            4.97 K      201.27 μs     ±8.91%         196 μs         288 μs
range             3.16 K      316.42 μs     ±9.32%         305 μs         471 μs

Comparison:
add random        5.26 K
tuple             5.21 K - 1.01x slower
picker            4.97 K - 1.06x slower
range             3.16 K - 1.66x slower

Which I find a little bit weird, as I would assume that range would be faster.

— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New
dillonoconnor
Is there any way to avoid the Hologram compiler running when using iex? It seems like the front-end code could potentially be disregarded...
New
thiagogsr
** (ArgumentError) expected :max_attempts to be a positive integer, got: {:@, [line: 10, column: 19], [{:max_attempts, [line: 10, column:...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews