SlideShare a Scribd company logo
Ruby performance
profiling
Minsk, SaM Solutions, 2013
Presented by Alexey Tulia
@AlexeyTulia, github.com/crible
Ruby. A programmer’s best friend
Ruby implementations
SLOW CODE
Практический опыт профайлинга и оптимизации производительности Ruby-приложений
Практический опыт профайлинга и оптимизации производительности Ruby-приложений
Reasons?
Garbage collection
Slow methods call
one iteration takes ~ 100ms
Garbage collection
Need one Gb?
Expect 128 GC calls!
You lose 128*0,1 = 12,8 sec
Allocated memory never returns to the system!
runs on every 8Mb of allocated memory
Garbage collection
More objects allocation -> more GC calls -> slow code
RUBY_HEAP_MIN_SLOTS=8000000
RUBY_GC_MALLOC_LIMIT=10000
Garbage collection tuning
performance patches
Ruby String performance
user system total real
21 chars 0.250000 0.000000 0.250000 ( 0.247459)
22 chars 0.250000 0.000000 0.250000 ( 0.246954)
23 chars 0.250000 0.000000 0.250000 ( 0.248440)
24 chars 0.480000 0.000000 0.480000 ( 0.478391)
25 chars 0.480000 0.000000 0.480000 ( 0.479662)
26 chars 0.480000 0.000000 0.480000 ( 0.481211)
27 chars 0.490000 0.000000 0.490000 ( 0.490404)
Ruby String performance
Heap strings
Shared strings
Embedded strings
struct RString {
long len;
char *ptr;
};
Ruby String performance
struct RString {
long len;
char * ptr;
VALUE shared;
};
struct RString {
char ary[RSTRING_EMBED_LEN_MAX +1];
}
RSTRING_EMBED_LEN_MAX = 23
Slow methods call
What can I do to improve performance?
Use C extensions or gems
Use plain SQL instead of frameworks
Use CPU and memory profiling
Use Rubinius or JRuby
THIS TALK IS
ABOUT THE TOOLS
TO FIX THE ISSUES
BEFOREYOU REWRITE
SH*T IN SCALA, PROFILE!
TOOLS FOR LINUX
LSOF
STRACE
LTRACE
TOOLS FOR CPU
Ruby-prof
perftools
perftools.rb
STRACE
trace system calls and signals
strace -cp <pid>
strace -ttTp <pid> -o <file>
% time seconds uses/call calls errors syscall
50,39 0,00064 0 1197 592 read
34,56 0,00044 0 609 writev
14,96 0,000019 0 1226 epoll_ctl
0,00 0,000000 0 4 close
0,00 0,000000 0 1 select
0,00 0,000000 0 4 socket
0,00 0,000000 0 4 4 connect
0,00 0,000000 0 1057 epoll_wait
100,0 0,000127 4134 596 total
strace -cp <pid>
LTRACE
trace dynamic library calls
ltrace -F <conf_file> -bg -x <symbol> -p pid
ltrace -F <conf_file> -bg -x <symbol> -p pid
-F <conf_file>
int mysql_real_query(addr,string,ulong);
void garbage_collect(void);
int memcached_set(addr,string,ulong,string,ulong);
ltrace -x garbage_collect
ltrace -x mysql_real_query
mysql_real_query(0x1c9e0500, "SET NAMES 'UTF8'", 16) = 0 <0.000324>
mysql_real_query(0x1c9e0500, "SET SQL_AUTO_IS_NULL=0", 22) = 0 <0.000322>
mysql_real_query(0x19c7a500, "SELECT * FROM `users`", 21) = 0 <1.206506>
mysql_real_query(0x1c9e0500, "COMMIT", 6) = 0 <0.000181>
RUBY-PROF
fast code profiler for Ruby
%self total self child calls name
------------------------------------------------------------------------
8.39 0.54 0.23 0.31 602 Array#each_index
7.30 0.41 0.20 0.21 1227 Integer#gcd
6.20 0.49 0.17 0.32 5760 Timecell#date
5.11 0.15 0.14 0.01 1 Magick::Image#to_blob
RUBY-PROF for CPU
KCachegrind
a tool for visualisation
http://kcachegrind.sourceforge.net
KCachegrind
KCachegrind
Практический опыт профайлинга и оптимизации производительности Ruby-приложений
PERFTOOLS.RB
google’s performance tools for ruby code
CPUPROFILE=/tmp/myprof 
pprof --calgrind ./myapp /tmp/myprof
gem install perftools.rb
RUBYOPT="-r`gem which perftools | tail -1`" 
ruby my_app.rb
PERFTOOLS.RB
CPUPROFILE_REALTIME = 1
CPU/wall time
CPUPROFILE_OBJECTS = 1
CPUPROFILE_METHODS = 1
Memory profiling
GC::Profiler.report
module «objspace»
Ruby-prof
Out of the box in Ruby 1.9
GC::Profiler.report
Out of the box in Ruby 1.9
module «objspace»
Ruby-prof for memory
rvm install 1.9.3-p448 --patch railexpress
gem install ruby-prof
$ ruby-1.9.3-p448 test.rb
Thread ID: 14925700
Fiber ID: 17378400
Total: 3842.242188
Sort by: self_time
%self total self wait child calls name
56.94 2187.766 2187.766 0.000 0.000 20000 String#chars
32.79 1259.953 1259.953 0.000 0.000 10000 Array#join
10.17 390.812 390.812 0.000 0.000 10000 Array#shuffle
0.01 3839.391 0.336 0.000 3839.055 1 Integer#times
0.00 1562.766 0.188 0.000 1562.578 10000
GDB.rb
$	
  sudo	
  gdb.rb	
  13074
	
  	
  GNU	
  gdb	
  (GDB)	
  7.0
	
  	
  Reading	
  symbols	
  from	
  /usr/bin/ruby...done.
	
  	
  Attaching	
  to	
  program:	
  /usr/bin/ruby,	
  process	
  13074
	
  	
  0x00007fa8b9cb3c93	
  in	
  select	
  ()	
  from	
  /lib/libc.so.6
	
  	
  (gdb)	
  ruby	
  eval	
  1+2
	
  	
  2
	
  	
  (gdb)	
  ruby	
  eval	
  Thread.list.count
	
  	
  17
	
  	
  (gdb)	
  ruby	
  objects	
  classes
	
  	
  	
  	
  	
  	
  	
  	
  	
  1	
  YAML::Syck::Resolver
	
  	
  	
  	
  	
  	
  	
  	
  	
  1	
  SystemStackError
	
  	
  	
  	
  	
  	
  	
  	
  	
  10	
  OptionParser::Switch::NoArgument
What should I remeber before CPU profiling?
Turn GC off (GC.disable)
do_smth is so slow!!!
Make it work
Make it right
Make it fast
When should I stop performance optimisation?
Premature optimization is the root of all evil
(c) Donald Knuth
TOOLS MAKE
PROFILING EASIER
LEARN THEM, USE
THEM
Questions?
Thank you!

More Related Content

PDF
Odoo Online platform: architecture and challenges
PDF
A little systemtap
PDF
Performance tweaks and tools for Linux (Joe Damato)
PDF
Debugging Ruby
PDF
Debugging Ruby Systems
PPTX
Scaling with Python: SF Python Meetup, September 2017
PDF
Monitoramento ambiental e alertas visuais com Zabbix - 3º Zabbix Meetup do In...
Odoo Online platform: architecture and challenges
A little systemtap
Performance tweaks and tools for Linux (Joe Damato)
Debugging Ruby
Debugging Ruby Systems
Scaling with Python: SF Python Meetup, September 2017
Monitoramento ambiental e alertas visuais com Zabbix - 3º Zabbix Meetup do In...

What's hot (20)

PDF
XS Boston 2008 Debugging Xen
PDF
Docker tips-for-java-developers
PDF
Redis as a message queue
PDF
Osol Pgsql
PDF
Elasticsearch (R)Evolution — You Know, for Search… by Philipp Krenn at Big Da...
PDF
XS Japan 2008 Isolation Japanese
PDF
Shrink to grow
ODP
Drizzle to MySQL, Stress Free Migration
PDF
Deep dive into PostgreSQL statistics.
PDF
37562259 top-consuming-process
PDF
Parallel Computing with R
PDF
5 issues
PPTX
Improving go-git performance
PDF
HDFSvTACHYON
PPTX
Rubyslava + PyVo #48
PDF
Adopting GraalVM - Scala eXchange London 2018
PDF
tdc2012
PPTX
agri inventory - nouka data collector / yaoya data convertor
PDF
nouka inventry manager
XS Boston 2008 Debugging Xen
Docker tips-for-java-developers
Redis as a message queue
Osol Pgsql
Elasticsearch (R)Evolution — You Know, for Search… by Philipp Krenn at Big Da...
XS Japan 2008 Isolation Japanese
Shrink to grow
Drizzle to MySQL, Stress Free Migration
Deep dive into PostgreSQL statistics.
37562259 top-consuming-process
Parallel Computing with R
5 issues
Improving go-git performance
HDFSvTACHYON
Rubyslava + PyVo #48
Adopting GraalVM - Scala eXchange London 2018
tdc2012
agri inventory - nouka data collector / yaoya data convertor
nouka inventry manager
Ad

Similar to Практический опыт профайлинга и оптимизации производительности Ruby-приложений (20)

PDF
Профилирование и оптимизация производительности Ruby-кода
PDF
Alexander Dymo - RubyConf 2014 - Ruby Performance Secrets and How to Uncover ...
ZIP
Rubinius 1.0 and more!
ODP
Debugging and Profiling Rails Application
PDF
Profiling ruby
PPTX
Ruby/rails performance and profiling
ODP
Performance Optimization of Rails Applications
PDF
Rubinius - What Have You Done For Me Lately?
PDF
Rails Performance
PDF
Scaling Rails with Ruby-prof -- Ruby Conf Kenya 2017 by Ben Hughes
PDF
Profiling Ruby
ODP
RailswayCon 2010 - Dynamic Language VMs
PDF
Rubinius - Improving the Rails ecosystem
PDF
Profiling and monitoring ruby & rails applications
PDF
High Performance Ruby - E4E Conference 2013
KEY
There and Back Again
PDF
How to Make Ruby CGI Script Faster - CGIを高速化する小手先テクニック -
PDF
ZOMG WHY IS THIS CODE SO SLOW
KEY
Use Ruby GC in full..
PDF
Ruby memory tips and tricks
Профилирование и оптимизация производительности Ruby-кода
Alexander Dymo - RubyConf 2014 - Ruby Performance Secrets and How to Uncover ...
Rubinius 1.0 and more!
Debugging and Profiling Rails Application
Profiling ruby
Ruby/rails performance and profiling
Performance Optimization of Rails Applications
Rubinius - What Have You Done For Me Lately?
Rails Performance
Scaling Rails with Ruby-prof -- Ruby Conf Kenya 2017 by Ben Hughes
Profiling Ruby
RailswayCon 2010 - Dynamic Language VMs
Rubinius - Improving the Rails ecosystem
Profiling and monitoring ruby & rails applications
High Performance Ruby - E4E Conference 2013
There and Back Again
How to Make Ruby CGI Script Faster - CGIを高速化する小手先テクニック -
ZOMG WHY IS THIS CODE SO SLOW
Use Ruby GC in full..
Ruby memory tips and tricks
Ad

More from Olga Lavrentieva (20)

PPTX
15 10-22 altoros-fact_sheet_st_v4
PPTX
Сергей Ковалёв (Altoros): Practical Steps to Improve Apache Hive Performance
PPTX
Андрей Козлов (Altoros): Оптимизация производительности Cassandra
PDF
Владимир Иванов (Oracle): Java: прошлое и будущее
PPTX
Brug - Web push notification
PDF
Александр Ломов: "Reactjs + Haskell + Cloud Foundry = Love"
PPTX
Максим Жилинский: "Контейнеры: под капотом"
PPTX
Александр Протасеня: "PayPal. Различные способы интеграции"
PPTX
Сергей Черничков: "Интеграция платежных систем в .Net приложения"
PPTX
Антон Шемерей «Single responsibility principle в руби или почему instanceclas...
PDF
Егор Воробьёв: «Ruby internals»
PDF
Андрей Колешко «Что не так с Rails»
PDF
Дмитрий Савицкий «Ruby Anti Magic Shield»
PPTX
Сергей Алексеев «Парное программирование. Удаленно»
PPTX
«Почему Spark отнюдь не так хорош»
PPTX
«Cassandra data modeling – моделирование данных для NoSQL СУБД Cassandra»
PPTX
«Практика построения высокодоступного решения на базе Cloud Foundry Paas»
PPTX
«Дизайн продвинутых нереляционных схем для Big Data»
PPTX
«Обзор возможностей Open cv»
PPTX
«Нужно больше шин! Eventbus based framework vertx.io»
15 10-22 altoros-fact_sheet_st_v4
Сергей Ковалёв (Altoros): Practical Steps to Improve Apache Hive Performance
Андрей Козлов (Altoros): Оптимизация производительности Cassandra
Владимир Иванов (Oracle): Java: прошлое и будущее
Brug - Web push notification
Александр Ломов: "Reactjs + Haskell + Cloud Foundry = Love"
Максим Жилинский: "Контейнеры: под капотом"
Александр Протасеня: "PayPal. Различные способы интеграции"
Сергей Черничков: "Интеграция платежных систем в .Net приложения"
Антон Шемерей «Single responsibility principle в руби или почему instanceclas...
Егор Воробьёв: «Ruby internals»
Андрей Колешко «Что не так с Rails»
Дмитрий Савицкий «Ruby Anti Magic Shield»
Сергей Алексеев «Парное программирование. Удаленно»
«Почему Spark отнюдь не так хорош»
«Cassandra data modeling – моделирование данных для NoSQL СУБД Cassandra»
«Практика построения высокодоступного решения на базе Cloud Foundry Paas»
«Дизайн продвинутых нереляционных схем для Big Data»
«Обзор возможностей Open cv»
«Нужно больше шин! Eventbus based framework vertx.io»

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
KodekX | Application Modernization Development
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Big Data Technologies - Introduction.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Empathic Computing: Creating Shared Understanding
MYSQL Presentation for SQL database connectivity
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Spectral efficient network and resource selection model in 5G networks
Encapsulation_ Review paper, used for researhc scholars
Machine learning based COVID-19 study performance prediction
Understanding_Digital_Forensics_Presentation.pptx
Unlocking AI with Model Context Protocol (MCP)
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Network Security Unit 5.pdf for BCA BBA.
KodekX | Application Modernization Development
20250228 LYD VKU AI Blended-Learning.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Review of recent advances in non-invasive hemoglobin estimation
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Reach Out and Touch Someone: Haptics and Empathic Computing
Big Data Technologies - Introduction.pptx
Chapter 3 Spatial Domain Image Processing.pdf
Encapsulation theory and applications.pdf
Approach and Philosophy of On baking technology
Empathic Computing: Creating Shared Understanding

Практический опыт профайлинга и оптимизации производительности Ruby-приложений