Skip to content

Instantly share code, notes, and snippets.

@rdp
Created October 21, 2022 06:06

Revisions

  1. rdp created this gist Oct 21, 2022.
    6 changes: 6 additions & 0 deletions test.cr
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    require "benchmark"
    require "uuid"

    Benchmark.ips do |x|
    x.report { UUID.random }
    end
    27 changes: 27 additions & 0 deletions test2.cr
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    require "benchmark"
    require "uuid"
    require "random"
    module Crystal::System::Random
    GENERATOR = SecureGenerator.new

    private class SecureGenerator
    getter buffer : Bytes = Bytes.new(8192).tap { |b| Crystal::System::Random.sys_getrandom b }
    getter index = 0

    def bytes(bytes : Bytes) : Nil
    if (offset = bytes.bytesize - (buffer.bytesize - index)) > 0
    (buffer + index).copy_to bytes
    @index = 0
    Crystal::System::Random.sys_getrandom buffer
    bytes(bytes + offset)
    else
    (buffer + index).copy_to bytes.to_unsafe, bytes.bytesize
    @index += bytes.bytesize
    end
    end
    end
    end

    Benchmark.ips do |x|
    x.report { UUID.random }
    end
    28 changes: 28 additions & 0 deletions test3.cr
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    require "benchmark"
    require "uuid"
    require "random"
    module Crystal::System::Random
    GENERATOR = SecureGenerator.new

    private class SecureGenerator
    getter buffer : Bytes = Bytes.new(8192).tap { |b| Crystal::System::Random.sys_getrandom b }
    getter index = 0

    def bytes(bytes : Bytes) : Nil
    if (offset = bytes.bytesize - (buffer.bytesize - index)) > 0
    (buffer + index).copy_to bytes
    @index = 0
    Crystal::System::Random.sys_getrandom buffer
    bytes(bytes + offset)
    else
    (buffer + index).copy_to bytes.to_unsafe, bytes.bytesize
    @index += bytes.bytesize
    end
    end
    end
    end

    Benchmark.ips do |x|
    m = Mutex.new
    x.report { m.synchronize {UUID.random }}
    end