Kohana 3 merging patch
Вторник, 23 февраля 2010 г.Рубрика: Web frameworks
Метки: Kohana | плагин
Просмотров: 4391
Подписаться на комментарии по RSS
Начитавшись Дмитрия Котерова, решил сделать "примочку", ускоряющую работу Kohana 3 за счет объединения файлов фреймворка в один большой. Сначала хотел сделать скрипт, автоматически проходящий по всем директориям и сливающий все файлы в один, однако из-за неясностей в разрешении зависимостей решил сделать нечто подобное форумному топику, когда в один файл объединяются автозагружаемые скрипты. В общем, оно получилось, правда, может ломаться при работе со сторонними библиотеками, с кохановскими вроде все нормально (к сожалению, мой модуль CheatSheet тоже ломается). Установка предельно простая -- копируем файл в APPPATH/classes и прописываем в bootstrap.php строку define('MERGED_CACHE_FILENAME', 'имя-файла'); , я пишу ее перед spl_autoload_register(). Также должен быть включен родной системный кэш Коханы.
(in English see below)
Для тестирования взял цмску Kohanut, результаты см. ниже. На малых нагрузках эффект почти незаметен (думаю, что при разросшемся скрипте кое-что все же будет), но при повышении конкурентности от 10 до 30 (если больше, увы, ломался Апач XAMPP) результат налицо, причем если среднее время на запрос и количество запросов в секунду увеличились сравнительно несильно (порядка 10 %), то разбежка по времени между самым коротким и самым длинным результатом уменьшилась почти в 2 раза! Думаю, что на больших скриптах может быть только лучше.
Впрочем, пока не рекомендую для использования в продакшне, нужно потестировать. Аналогично хочу сделать версию для ветки 2.х с явным прицелом на production use, поскольку там разрабатываемая с моим участием система разрослась до нескольких мегабайт.
In English:
After re-readind of Dmitry Koterov's article (http://dklab.ru/chicken/nablas/49.html) I've decided to apply his idea (merge engine files to accelerate script loading and performance) to Kohana 3 framework. First, I intended to make script that could walk through Ko3 filesystem and merge files, but could not solve dependency resolving problem. So I make Kohana Core patch that merges only autoloaded files (inspired by forum topic http://forum.dklab.ru/viewtopic.php?p=156550). After some testing I can say that it seems to work properly with Kohana 3 scripts, but can fail on some vendor libs (and my CheatSheet module crashes too). Installation is extremly simple -- copy file in APPPATH/classes and put define('MERGED_CACHE_FILENAME', 'file-name'); somewhere in bootstrap.php (I put it before spl_autoload_register() invocation). Native Ko3 system cache should also be turned on.
For testing I took Kohanut CMS. Results can be seen below. On small concurrensy it was almost no result (think this CMS is too small to see it), but after changing concurrensy from 10 to 30 it was obviousely appeared (unfortunately at bigger concurrensy values my Windows XAMPP Apache fails). You can see that mean request time and req./sec increased slightly (about 10 %), but time gap between the longest and the shortest requests was decreased almost by one-half! Hope that for bigger sripts it will be better.
Please do not use this patch in production, only for tests and bug reports! I want to port this to Kohana 2.x branch as more production-ready, but after some testing and bugs collection.
Скачать/Download 28 (zipped ~ 3KiB). Инструкция в комментарии класса / See class comment for instruction.
Windows Vista Home Basic, XAMPP 1.7.1, Apache/2.2.11, eAccelerator 0.9.5.3 enabled
ab -n 500 -c 10 http://kohanut3.loc/
no cache
Concurrency Level: 10
Requests per second: 1.62 [#/sec] (mean)
Time per request: 6164.215 [ms] (mean)
Time per request: 616.421 [ms] (mean, across all concurrent requests)
Transfer rate: 7.91 [Kbytes/sec] received
Percentage of the requests served within a certain time (ms)
50% 6011
66% 6042
75% 6078
80% 6109
90% 6264
95% 6430
98% 8333
99% 8864
100% 9236 (longest request)
file path cache only
Concurrency Level: 10
Requests per second: 1.71 [#/sec] (mean)
Time per request: 5861.930 [ms] (mean)
Time per request: 586.193 [ms] (mean, across all concurrent requests)
Transfer rate: 8.31 [Kbytes/sec] received
Percentage of the requests served within a certain time (ms)
50% 5788
66% 5804
75% 5821
80% 5842
90% 5950
95% 6131
98% 6414
99% 7146
100% 7291 (longest request)
file path cache + merged scripts file
Concurrency Level: 10
Requests per second: 1.71 [#/sec] (mean)
Time per request: 5841.189 [ms] (mean)
Time per request: 584.119 [ms] (mean, across all concurrent requests)
Transfer rate: 8.34 [Kbytes/sec] received
Percentage of the requests served within a certain time (ms)
50% 5755
66% 5769
75% 5793
80% 5812
90% 5885
95% 6009
98% 6693
99% 6876
100% 6992 (longest request)
***More concurrensy***
ab -n 300 -c 30 http://kohanut3.loc/
no cache
Concurrency Level: 30
Requests per second: 3.54 [#/sec] (mean)
Time per request: 8473.872 [ms] (mean)
Time per request: 282.462 [ms] (mean, across all concurrent requests)
Transfer rate: 17.25 [Kbytes/sec] received
Percentage of the requests served within a certain time (ms)
50% 7703
66% 8058
75% 8353
80% 8552
90% 9850
95% 12696
98% 13995
99% 14364
100% 14488 (longest request)
file path cache only
Concurrency Level: 30
Requests per second: 4.44 [#/sec] (mean)
Time per request: 6763.141 [ms] (mean)
Time per request: 225.438 [ms] (mean, across all concurrent requests)
Transfer rate: 21.62 [Kbytes/sec] received
Percentage of the requests served within a certain time (ms)
50% 5894
66% 6068
75% 6193
80% 6340
90% 8978
95% 11273
98% 11742
99% 12131
100% 12182 (longest request)
file path cache + merged scripts file
Concurrency Level: 30
Requests per second: 4.79 [#/sec] (mean)
Time per request: 6261.806 [ms] (mean)
Time per request: 208.727 [ms] (mean, across all concurrent requests)
Transfer rate: 23.35 [Kbytes/sec] received
Percentage of the requests served within a certain time (ms)
50% 5800
66% 5856
75% 5935
80% 5976
90% 6447
95% 7824
98% 9137
99% 9499
100% 9734 (longest request)
Комментариев: 5
Т.е. этот модуль будет все загружаемые файлы объединять в один, а результат куда, в кеше? А если разные контроллеры требуют разных классов, как себя ведет модуль?
Самый большой недостаток, что создается один файл для всех запросов. Запросов могут вообще не использовать те классы. У меня тоже есть такой модуль в арсенале http://github.com/FerumFlex/kohana-super-cache. Единственное, что он оформлен модулем и создает кэш для каждого файла отдельно.
Максим да, все, что проходит через autoload, будет сливаться в один большой файл кэша. При последующих запросах этот файл будет require-иться вместо множества мелких.
Если разные контроллеры требуют разных классов, то все эти классы и будут слеплены в один файл кэша.
ANT да, следующей версией я думал сделать раздельный кэш для разных запросов (админка, например, лишь в малой части перекрывается с пользовательской стороной). Спасибо за ссылку, если бы я увидел ее раньше, то, наверное, не писал бы свой вариант, ожидая продолжения вашего
Тем не менее, модульный подход здесь мне кажется не слишком подходит, возможно, ошибаюсь.
Спасибо, сейчас буду пробывать. Возникли проблемы при длительных продолжительных нагрузках при включении файлов фреймворка.
Посмотрите более новую версию патча http://kupreev.com/page/kohana-merging-patch2