Prima misura, poi ottimizza
La regola d'oro: mai tirare a indovinare. Benchmark di Ruby misura che cosa è davvero lento – spesso non è ciò che pensi. Un classico: += sulle stringhe crea ogni volta una stringa nuova, la “paletta” << estende quella esistente:
require "benchmark"
n = 5_000
plus = Benchmark.realtime do
s = ""
n.times { s += "x" }
end
shovel = Benchmark.realtime do
s = ""
n.times { s << "x" }
end
{ plus: plus.round(4), shovel: shovel.round(4) }Dietro c'è il grande tema delle allocazioni: ogni oggetto intermedio superfluo costa tempo e memoria. E l'ottimizzazione più rapida di tutte: il codice che non viene eseguito affatto.
$ gem install benchmark-ips stackprof
# benchmark-ips: how many times per second? (more telling than one run)
# stackprof: WHERE does the program spend its time?Concorrenza: con Thread Ruby fa più cose “contemporaneamente”. In MRI tutti i thread condividono un unico interprete (il GVL) – i guadagni reali si vedono quindi soprattutto durante le attese (rete, file); per il parallelismo sulla CPU ci sono i Ractor. Il browser non ha thread veri, perciò qui Thread e sleep sono simulati (in modo cooperativo, con un tempo virtuale) – ma l'API è quella vera:
fetches = ["clients", "projects", "times"].map do |name|
Thread.new do
sleep 1 # download di rete simulato
"#{name}: loaded"
end
end
fetches.map(&:value)Tre “download”, avviati con Thread.new, raccolti con value – sul tuo computer questo richiede il tempo di un download invece di tre. E dato che i nostri thread simulati si danno il turno a ogni sleep, puoi persino osservare l'alternanza nell'output:
threads = 2.times.map do |i|
Thread.new do
3.times do |n|
puts "thread #{i}: step #{n}"
sleep 0.1
end
end
end
threads.each(&:join)
"done"A proposito, sotto il cofano della nostra simulazione ci sono le Fiber: mini-programmi cooperativi che si passano il controllo in modo esplicito – la base di molte librerie asincrone. Puoi usarle anche direttamente:
narrator = Fiber.new do
Fiber.yield "Chapter 1: Bacon"
Fiber.yield "Chapter 2: More bacon"
"The end"
end
[narrator.resume, narrator.resume, narrator.resume]slow_report qui sotto scorre le voci una volta per ogni progetto – con molti progetti diventa quadratico. Scrivi fast_report, che produce lo stesso risultato con un unico passaggio di group_by. Misura la differenza con Benchmark!entries = 500.times.map { |i| { project: "P#{i % 5}", hours: 1.0 } }
def slow_report(entries)
entries.map { |e| e[:project] }.uniq.to_h do |p|
[p, entries.select { |e| e[:project] == p }.sum { |e| e[:hours] }]
end
end
# def fast_report(entries)
# ...
# end
# require "benchmark"
# { slow: Benchmark.realtime { 50.times { slow_report(entries) } }.round(3),
# fast: Benchmark.realtime { 50.times { fast_report(entries) } }.round(3) }