Last active
April 17, 2025 11:49
-
-
Save luismendes070/0a60881fc8c3715363dec0347491ecea to your computer and use it in GitHub Desktop.
Deepseek prompt medir desempenho api em ruby on rails #benchmark #newrelic_rpm
This file contains hidden or 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
# Medindo Desempenho de API em Ruby on Rails | |
Para medir o desempenho de uma API em Ruby on Rails, existem várias abordagens e ferramentas que você pode utilizar. Aqui estão algumas das principais: | |
## 1. Benchmarks Básicos | |
```ruby | |
# Em algum lugar do seu controller ou service | |
start_time = Time.now | |
# Código que você quer medir | |
end_time = Time.now | |
elapsed_time = end_time - start_time | |
Rails.logger.info "Tempo de execução: #{elapsed_time} segundos" | |
``` | |
## 2. Gem 'benchmark' | |
Ruby possui um módulo Benchmark nativo: | |
```ruby | |
require 'benchmark' | |
result = Benchmark.measure do | |
# Código da sua API | |
end | |
puts result # => 0.000000 0.000000 0.000000 ( 0.000000) | |
``` | |
## 3. Gems Especializadas | |
### rack-mini-profiler | |
```ruby | |
# Gemfile | |
gem 'rack-mini-profiler' | |
# Depois de instalado, mostra um widget na página com tempos de execução | |
``` | |
### ruby-prof (para análise detalhada) | |
```ruby | |
gem 'ruby-prof' | |
# Exemplo de uso: | |
result = RubyProf.profile do | |
# Código para analisar | |
end | |
printer = RubyProf::FlatPrinter.new(result) | |
printer.print(STDOUT) | |
``` | |
### newrelic_rpm (para monitoramento em produção) | |
```ruby | |
gem 'newrelic_rpm' | |
``` | |
## 4. Testes de Carga | |
### Apache Benchmark (ab) | |
```bash | |
ab -n 1000 -c 10 http://localhost:3000/api/endpoint | |
``` | |
### Siege | |
```bash | |
siege -c 100 -t 1M http://localhost:3000/api/endpoint | |
``` | |
### JMeter (para testes mais complexos) | |
## 5. Logs do Rails | |
Ative logging detalhado: | |
```ruby | |
# config/environments/development.rb | |
config.log_level = :debug | |
``` | |
## 6. ActiveSupport::Notifications | |
O Rails fornece instrumentação interna: | |
```ruby | |
ActiveSupport::Notifications.subscribe "process_action.action_controller" do |name, start, finish, id, payload| | |
duration = finish - start | |
Rails.logger.info "#{payload[:controller]}##{payload[:action]}: #{duration} sec" | |
end | |
``` | |
## 7. Database Performance | |
Verifique queries lentas: | |
```ruby | |
# Gemfile | |
gem 'activerecord-import' | |
gem 'bullet' | |
# Verifique o log/development.log para queries N+1 | |
``` | |
## 8. Monitoramento Contínuo (para produção) | |
- New Relic | |
- Skylight | |
- Scout APM | |
- Datadog APM | |
## Exemplo Completo de Controller com Benchmarks | |
```ruby | |
class Api::V1::ProductsController < ApplicationController | |
before_action :set_product, only: [:show] | |
def index | |
benchmark = Benchmark.measure do | |
@products = Product.all | |
render json: @products | |
end | |
log_performance(benchmark) | |
end | |
def show | |
benchmark = Benchmark.measure do | |
render json: @product | |
end | |
log_performance(benchmark) | |
end | |
private | |
def set_product | |
@product = Product.find(params[:id]) | |
end | |
def log_performance(benchmark) | |
Rails.logger.info "API Performance: #{controller_name}##{action_name}" | |
Rails.logger.info "User CPU time: #{benchmark.utime}" | |
Rails.logger.info "System CPU time: #{benchmark.stime}" | |
Rails.logger.info "Total CPU time: #{benchmark.total}" | |
Rails.logger.info "Real time: #{benchmark.real}" | |
end | |
end | |
``` | |
Lembre-se que para medições precisas em produção, você deve considerar: | |
- Testar em ambiente similar ao produtivo | |
- Aquecer a aplicação antes dos testes | |
- Executar múltiplos testes e calcular médias | |
- Monitorar recursos do servidor (CPU, memória, I/O) durante os testes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment