Skip to content

Instantly share code, notes, and snippets.

@paulohrpinheiro
Created October 3, 2025 22:59
Show Gist options
  • Select an option

  • Save paulohrpinheiro/107592b9be82b4da7f0b3835ca994152 to your computer and use it in GitHub Desktop.

Select an option

Save paulohrpinheiro/107592b9be82b4da7f0b3835ca994152 to your computer and use it in GitHub Desktop.
raku benchmark ollama LLMs
#!/usr/bin/env raku
MIT License
Copyright (c) 2025, Paulo Henrique Rodrigues Pinehiro (paulohrpinheiro)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
use HTTP::Tiny;
use JSON::Fast;
constant BASE_URL = "http://127.0.0.1:11434";
constant PROMPT = q:to/END_OF_PROMPT/;
Escreva um programa na linguagem brainfuck que use o crivo de eratóstenes
para descobrir os cinco primeiros números primos e imprimí-los. Quero apenas
a listagem do programa, sem explicações, plano de trabalho ou qualquer outra
informação.
Apenas o código fonte.
Toda a saída que você mandar, deve obedecer essa estrutura JSON:
{
"llm": "aqui vai o seu nome real de modelo LLM",
"source": "aqui vai o programa que você gerar",
"think": "qualquer saída que seja apenas pensamento ou construção de um plano",
"explain": {
"language": "qualquer explicação sobre a linguagem",
"algorithm": "qualquer explicação sobre o algoritmo"
},
"references": ["referencia de livro", "referencia de site", "qualquer outra referencia"]
}
END_OF_PROMPT
sub http-get($endpoint) {
return HTTP::Tiny.new.get("{BASE_URL}/{$endpoint}");
}
sub http-post($endpoint, %data) {
my $uri = "{BASE_URL}/$endpoint";
my $content = to-json(%data);
my %headers = %("Content-Type" => "application/json");
return HTTP::Tiny.new.post($uri, content => $content, headers => %headers);
}
sub round-mili($value) {
my $num = ($value // 0).Num;
return round($num, 0.0001);
}
sub get-available-models() {
say "=> Buscando modelos via API...";
my $response = http-get("api/tags");
my $content-buf = $response<content>;
my $json-str = $content-buf.decode('utf-8');
my $data = from-json($json-str);
return $data<models>.map({ $_<name> }).sort;
}
sub run-model(Str $model, Str $prompt) {
my %json;
my %payload = %(
model => $model,
prompt => $prompt,
stream => False,
format => "json"
);
my $response = http-post('api/generate', %payload);
return from-json($response<content>.decode);
}
sub normalize-json(%json) {
my $promptEvalCount = %json<prompt_eval_count>:delete;
my $promptEvalDuration = round-mili(%json<prompt_eval_duration>:delete);
my $evalCount = %json<eval_count>:delete;
my $evalDuration = round-mili(%json<eval_duration>:delete);
my $loadDuration = round-mili(%json<load_duration>:delete);
%json<context>:delete;
%json<metrics> = %(
prompt => %(
count => $promptEvalCount,
duration => $promptEvalDuration / 1_000_000_000,
speed => $promptEvalCount / $promptEvalDuration if $promptEvalDuration > 0,
),
eval => %(
count => $evalCount,
duration => $evalDuration / 1_000_000_000,
speed => $evalCount / $evalDuration if $evalDuration > 0,
),
total => %(
load => $loadDuration / 1_000_000_000,
duration => 0,
),
units => %(
durations => "seconds",
counts => "tokens/second",
),
);
}
sub free-gpu(Str $model) {
my %payload = %(
model => $model,
keep_alive => 0
);
http-post('api/generate', %payload);
}
sub verify-connection {
try {
my $content = http-get("/api/tags");
unless $content {
note "Ollama não está respondendo em {BASE_URL}";
note "Verifique se o Ollama está rodando: ollama serve";
exit 1;
}
}
if $! {
note "Erro de conexão: $!";
exit 1;
}
}
sub MAIN() {
say "Iniciando benchmark de modelos Ollama...";
verify-connection();
my @models = get-available-models();
if @models.elems == 0 {
note "Nenhum modelo encontrado!";
exit 1;
}
say "!! Encontrados {@models.elems} modelos:";
say " $_" for @models;
say "";
my $total-models = @models.elems;
my $current = 0;
for @models -> $model {
$current++;
say "=" x 60;
say "Executando: $model ($current/$total-models)";
say "=" x 60;
my $start-time = now;
my %response = run-model($model, PROMPT);
my $end-time = now;
normalize-json(%response);
my %result = from-json(%response<response>);
%result<metrics> = %response<metrics>;
%result<metrics><total><duration> = round-mili($end-time - $start-time);
my $safe-model = $model.subst('/', '_', :g).subst(':', '_', :g);
my $filename = "output_{$safe-model}.json";
spurt $filename, to-json(%result, :pretty);
say "Salvo: $filename";
say "Estatisticas:";
say to-json(%result<metrics>, :pretty);#, :sorted-keys);
say "\nLiberando GPU...";
free-gpu($model);
if $current < $total-models {
say "Aguardando 5 segundos...\n";
sleep 5;
}
}
say "Benchmark concluido!";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment