Skip to content

Instantly share code, notes, and snippets.

@rdp
Created October 21, 2022 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdp/2ed3e38f42c44b7ab5c96d017f41ea46 to your computer and use it in GitHub Desktop.
Save rdp/2ed3e38f42c44b7ab5c96d017f41ea46 to your computer and use it in GitHub Desktop.
require "benchmark"
require "uuid"
Benchmark.ips do |x|
x.report { UUID.random }
end
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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment