Created
September 5, 2016 18:26
-
-
Save anonymous/305446a60a1a28bd0587a74279c32ce8 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
# coding: utf-8 | |
require 'benchmark' | |
require 'securerandom' | |
def get_random_word(len) | |
alphabet = "abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ0123456789" | |
alphabet_len = alphabet.size | |
random_word = "" | |
len.times do | |
random_index = SecureRandom.random_number(alphabet_len) | |
random_word << alphabet[random_index] # Concaténation du caractère | |
end | |
return random_word # Retourner le résultat | |
end | |
#Retourne un mot aléatoire de len caractères (version récursive) | |
def get_random_word_recur(len, random_word="") | |
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' | |
alphabet_size = alphabet.size | |
if len == 0 | |
return random_word | |
else | |
random_char = alphabet[SecureRandom.random_number(alphabet_size)] | |
random_word << random_char | |
return get_random_word_recur(len - 1, random_word) | |
end | |
end | |
N = 1e5.to_i | |
Benchmark.bmbm do |x| | |
x.report("times") { N.times { get_random_word(10) } } | |
x.report("recur") { N.times { get_random_word_recur(10) } } | |
end | |
__END__ | |
Rehearsal ----------------------------------------- | |
times 0.570000 0.000000 0.570000 ( 0.568214) | |
recur 0.760000 0.000000 0.760000 ( 0.760474) | |
-------------------------------- total: 1.330000sec | |
user system total real | |
times 0.560000 0.000000 0.560000 ( 0.559365) | |
recur 0.760000 0.000000 0.760000 ( 0.757587) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment