-
Notifications
You must be signed in to change notification settings - Fork 140
[potashin] optimization #107
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
potashin
wants to merge
2
commits into
hardcode-dev:master
Choose a base branch
from
potashin:feature/potashin-optimization
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
result.json | ||
data*.txt | ||
|
||
/tmp/* | ||
!/tmp/.keep | ||
|
||
/tmp/memory_profiler/* | ||
!/tmp/memory_profiler/ | ||
!/tmp/memory_profiler/.keep | ||
|
||
/tmp/ruby_prof/* | ||
!/tmp/ruby_prof/ | ||
!/tmp/ruby_prof/.keep | ||
|
||
/tmp/stackprof/* | ||
!/tmp/stackprof/ | ||
!/tmp/stackprof/.keep | ||
|
||
/tmp/valgrind/* | ||
!/tmp/valgrind/ | ||
!/tmp/valgrind/.keep | ||
|
||
# Ignore MacOS system files | ||
.DS_Store |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
3.3.0 |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
source 'https://rubygems.org' | ||
|
||
gem 'memory_profiler' | ||
gem 'ruby-prof' | ||
gem 'stackprof' | ||
gem 'rspec' | ||
gem 'rspec-benchmark' |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
GEM | ||
remote: https://rubygems.org/ | ||
specs: | ||
benchmark-malloc (0.2.0) | ||
benchmark-perf (0.6.0) | ||
benchmark-trend (0.4.0) | ||
diff-lcs (1.5.1) | ||
memory_profiler (1.0.1) | ||
rspec (3.13.0) | ||
rspec-core (~> 3.13.0) | ||
rspec-expectations (~> 3.13.0) | ||
rspec-mocks (~> 3.13.0) | ||
rspec-benchmark (0.6.0) | ||
benchmark-malloc (~> 0.2) | ||
benchmark-perf (~> 0.6) | ||
benchmark-trend (~> 0.4) | ||
rspec (>= 3.0) | ||
rspec-core (3.13.0) | ||
rspec-support (~> 3.13.0) | ||
rspec-expectations (3.13.0) | ||
diff-lcs (>= 1.2.0, < 2.0) | ||
rspec-support (~> 3.13.0) | ||
rspec-mocks (3.13.0) | ||
diff-lcs (>= 1.2.0, < 2.0) | ||
rspec-support (~> 3.13.0) | ||
rspec-support (3.13.1) | ||
ruby-prof (1.7.0) | ||
stackprof (0.2.26) | ||
|
||
PLATFORMS | ||
arm64-darwin-23 | ||
ruby | ||
|
||
DEPENDENCIES | ||
memory_profiler | ||
rspec | ||
rspec-benchmark | ||
ruby-prof | ||
stackprof | ||
|
||
BUNDLED WITH | ||
2.5.4 |
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
# Case-study оптимизации | ||
|
||
## Актуальная проблема | ||
В нашем проекте возникла серьёзная проблема. | ||
|
||
Необходимо было обработать файл с данными, чуть больше ста мегабайт. | ||
|
||
У нас уже была программа на `ruby`, которая умела делать нужную обработку. | ||
|
||
Она успешно работала на файлах размером пару мегабайт, но для большого файла она работала слишком долго, и не было понятно, закончит ли она вообще работу за какое-то разумное время. | ||
|
||
Я решил исправить эту проблему, оптимизировав эту программу. | ||
|
||
## Формирование метрики | ||
Для того, чтобы понимать, дают ли мои изменения положительный эффект на быстродействие программы я придумал использовать такую метрику: количество потребляемой памяти при просчете 100к записей (885 мб на старте, 11.4 секунды) | ||
|
||
## Гарантия корректности работы оптимизированной программы | ||
Программа поставлялась с тестом. Выполнение этого теста в фидбек-лупе позволяет не допустить изменения логики программы при оптимизации. | ||
|
||
## Feedback-Loop | ||
Для того, чтобы иметь возможность быстро проверять гипотезы я выстроил эффективный `feedback-loop`, который позволил мне получать обратную связь по эффективности сделанных изменений за *время, которое у вас получилось* | ||
|
||
Вот как я построил `feedback_loop`: профилирование - изменение кода - тестирование – бенчмаркинг – откат при отсутствии разницы от оптимизации/сохранение результатов | ||
|
||
## Вникаем в детали системы, чтобы найти главные точки роста | ||
Для того, чтобы найти "точки роста" для оптимизации я воспользовался memoty_profiler, ruby-prof (allocation/memory), stackprof (allocation), valgrind | ||
|
||
Вот какие проблемы удалось найти и решить | ||
|
||
### Ваша находка №1 | ||
- memory_profiler показал, что больше всего памяти `3587123560` аллоцируется в `task-2.rb:74` (по классу лидирует`5212433896 Array`, что похоже на то, что происходит в `task-2.rb:74`) | ||
- вместо создания нового массива `sessions = sessions + [parse_session(line)] if cols[0] == 'session'` будем использовать пуш `<<` в уже определенный массив (для аналогично для `users`). | ||
- метрика снизилась с 885 до 287 мб | ||
- профилировщик показывает `1305579360 task-2.rb:128` как лидирующую позицию. Количество аллоцированных массивов снизилось до `1499267656 Array` | ||
|
||
### Ваша находка №2 | ||
- memory_profiler показал, что больше всего памяти `1305579360` аллоцируется в `task-2.rb:128` (по классу лидирует`1499267656 Array`, что похоже на то, что происходит в `task-2.rb:128`) | ||
- заменяем `sessions.select { |session| session['user_id'] == user['id'] }` на поиск по предварительно сформированному хэшу `sessions_by_user = sessions.group_by { |session| session['user_id'] }` | ||
- метрика снизилась с 287 до 140 мб | ||
- профилировщик показывает `120416072 task-2.rb:132` как лидирующую позицию. Количество аллоцированных массивов снизилось до `206505392 Array`, лидирующее место теперь занимает `344381297 String`. | ||
|
||
### Ваша находка №3 | ||
- memory_profiler показал, что больше всего памяти `120416072` аллоцируется в `task-2.rb:132` (по классу лидирует `344381297 String`, что не похоже на то, что происходит в `task-2.rb:132`, поскольку там происходят операции с массивами, а не строками). | ||
- вместо `users_objects = users_objects + [user_object]` использую `users_objects << user_object` | ||
- метрика снизилась незначительно, будем считать, что это те же 140 мб | ||
- профилировщик показывает `97472465 task-2.rb:169` как лидирующую позицию. Количество аллоцированных массивов снизилось до `86230952 Array`, лидирующее место по-прежнему занимает `344381297 String`. | ||
|
||
### Ваша находка №4 | ||
- memory_profiler показал, что больше всего памяти `97472465` аллоцируется в `task-2.rb:169` (по классу лидирует `344381297 String`, что похоже на то, что происходит в `task-2.rb:169`) | ||
- заменяю `user.sessions.map{|s| s['date']}.map {|d| Date.parse(d)}.sort.reverse.map { |d| d.iso8601 }` на `user.sessions.map{|s| s['date']}.sort { |d1, d2| d2 <=> d1 }` | ||
- метрика снизилась с 140 до 133 мб | ||
- профилировщик показывает `96369656 json-2.7.2/lib/json/common.rb:220` как лидирующую позицию. Количество аллоцированных строк снизилось до `313934727 String`, это по-прежнему лидирующая позиция. | ||
|
||
### Ваша находка №5 | ||
- профилировщик показывает `96369656 json-2.7.2/lib/json/common.rb:220` как лидирующую позицию | ||
- вместо записи/чтения файла из каждого треда, агрегирую репорты из каждого треда, после чего 1 раз пишу ее содержимое в файл | ||
- метрика снизилась с 133 до 58 мб | ||
- профилировщик показывает `48221760 task-2.rb:72` как лидирующую позицию. Количество аллоцированных строк снизилось до `160207766 String`, это по-прежнему лидирующая позиция. | ||
|
||
### Ваша находка №6 | ||
- профилировщик показывает `48221760 task-2.rb:72` как лидирующую позицию, но дальнейшие попытки оптимизации не приводят к снижению потребляемой памяти: основной точкой роста является ограничение накапливаемых данных | ||
- переписываю программу в потоковом стиле (накапливаем данные только по 1 пользователю и его сессиям за раз, после накопления собираем статистику, пишем в файл и начинаем сначала) | ||
- снизилась до 21мб для 100к (для всего файла тоже 21мб) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. да, самое кайфовое, что теперь любой объём данных так можно перелопатить |
||
- количество строк сократилось до `51749209 String` | ||
|
||
## Результаты | ||
В результате проделанной оптимизации наконец удалось обработать файл с данными. | ||
Удалось улучшить метрику системы с 885мб до 21мб и уложиться в заданный бюджет (70мб). | ||
|
||
## Защита от регрессии производительности | ||
Для защиты от потери достигнутого прогресса при дальнейших изменениях программы были написаны тесты на асимптотику, время работы и количество аллоцированных объектов на 10к строк |
This file was deleted.
Oops, something went wrong.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
require_relative '../task-2' | ||
|
||
require 'memory_profiler' | ||
|
||
report = MemoryProfiler.report do | ||
GC.disable | ||
work | ||
end | ||
|
||
report.pretty_print |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
require_relative '../task-2' | ||
|
||
require 'ruby-prof' | ||
|
||
RubyProf.measure_mode = RubyProf::ALLOCATIONS | ||
|
||
result = RubyProf.profile do | ||
GC.disable | ||
work | ||
end | ||
|
||
printer = RubyProf::FlatPrinter.new(result) | ||
printer.print(File.open('tmp/ruby_prof/flat.txt', 'w+')) | ||
|
||
# printer = RubyProf::DotPrinter.new(result) | ||
# printer.print(File.open('tmp/ruby_prof/graphviz.dot', 'w+')) | ||
|
||
printer = RubyProf::GraphHtmlPrinter.new(result) | ||
printer.print(File.open('tmp/ruby_prof/graph.html', 'w+')) | ||
|
||
printer = RubyProf::CallStackPrinter.new(result) | ||
printer.print(File.open('tmp/ruby_prof/callstack.html', 'w+')) |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
require_relative '../task-2' | ||
|
||
require 'ruby-prof' | ||
|
||
RubyProf.measure_mode = RubyProf::MEMORY | ||
|
||
result = RubyProf.profile do | ||
GC.disable | ||
work | ||
end | ||
|
||
|
||
printer = RubyProf::CallTreePrinter.new(result) | ||
printer.print(path: 'tmp/ruby_prof', profile: 'profile') |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
require 'rspec' | ||
require 'rspec-benchmark' | ||
require_relative '../task-2' | ||
|
||
RSpec.describe 'work' do | ||
include RSpec::Benchmark::Matchers | ||
|
||
it 'should be linear' do | ||
expect { |number, _| | ||
`head -n #{number * 1000} data_large.txt > data.txt` | ||
|
||
work | ||
}.to perform_linear.in_range(1, 100) | ||
end | ||
|
||
it 'should perform under 5 seconds' do | ||
`head -n 1000000 data_large.txt > data.txt` | ||
|
||
expect { work }.to perform_under(5).sec | ||
end | ||
|
||
it 'should not allocate more than 110000 objects' do | ||
`head -n 10000 data_large.txt > data.txt` | ||
|
||
expect { work }.to perform_allocation(109643) | ||
end | ||
end |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
require_relative '../task-2' | ||
|
||
require 'stackprof' | ||
|
||
StackProf.run(mode: :object, out: "tmp/stackprof/allocation_#{Time.now.to_i}.dump", raw: true) do | ||
GC.disable | ||
work | ||
end |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍