Публикации с меткой «memory»

Блог python на хабрахабре

Язык программирования Python / Профилирование python приложений

Краткая заметка с линками и примерами о профайлинге:
  1. производительности: hotshot + визуализатор логов kcachegrind (Linux, KDE. Подскажите аналоги — уверен, найдутся)
  2. использование памяти: dowser с web-интерфейсом

Lazy Crazy Coder's blog

Using __slots__ for optimisation in python

Do you know anything about python's slots construction? I did't before this day.

But slots in the python exists from version 2.2. It's main purpose is memory optimisation because it allow to get rid of dict object, which created by interpreter for each instance of class.

If you create many small objects, with predefined structure, and meet a memory limit, than slots can help you to overcome that limitation.

But remember, that early optimisation is the root of all evil. Furthermore, slots has many limitations that you need to be aware. For example, you can't use multiple inheritance and must be very careful if usual inheritance too.

As I am very interested in the different optimisation technics, I desided to make a small test.

I have found an interesting python library, that helps to measure memory usage. It's name is Guppy.

So, I write this simple test, which create tuples of one million instances of simple class. Every object hold two attibute 'a' and 'b'. First class is standart, second uses slots to optimise memory footprint.


import sys
import guppy
import time

class Test1(object):
    def __init__(self):
        self.a = 1
        self.b = 2

class Test2(object):
    __slots__ = ('a', 'b')
    def __init__(self):
        self.a = 1
        self.b = 2

if __name__ == '__main__':
    num = 1000000
    cls = Test1

    if len(sys.argv) == 2:
        if sys.argv[1] == '2':
            cls = Test2

    l = tuple(cls() for i in xrange(num))

    h = guppy.hpy()
    print h.heap()

If you run this program without params, it would create a 1000000 usual instances and output something like that:

Partition of a set of 2020446 objects. Total size = 169426216 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0 1000000  49 136000000  80 136000000  80 dict of __main__.Test1
     1 1000000  49 28000000  17 164000000  97 __main__.Test1
     2   4901   0  4178264   2 168178264  99 tuple
     3   9527   0   611920   0 168790184 100 str
     4   1416   0    96288   0 168886472 100 types.CodeType
     5     61   0    89704   0 168976176 100 dict of module
     6    155   0    85784   0 169061960 100 dict of type
     7   1342   0    75152   0 169137112 100 function
     8    170   0    73360   0 169210472 100 type
     9    119   0    68408   0 169278880 100 dict of class

Now run program with one argument '2'. In this case, output will look like that:

Partition of a set of 1020446 objects. Total size = 33426216 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0 1000000  98 28000000  84  28000000  84 __main__.Test2
     1   4901   0  4178264  12  32178264  96 tuple
     2   9527   1   611920   2  32790184  98 str
     3   1416   0    96288   0  32886472  98 types.CodeType
     4     61   0    89704   0  32976176  99 dict of module
     5    155   0    85784   0  33061960  99 dict of type
     6   1342   0    75152   0  33137112  99 function
     7    170   0    73360   0  33210472  99 type
     8    119   0    68408   0  33278880 100 dict of class
     9     65   0    49928   0  33328808 100 dict (no owner)

Pay attention at the top line in the first stats. It states, that 136000000 was reserved to the "dict of main.Test1". Seconds stats does not countain such line because of slots was used for optimisation.

Now we can calculate a profit of the slots in that particular case. It is (136000000 + 28000000) / 28000000 or 5 times! Second run reqire a 5 times less memory than first! It's amazing! But remember about warning you was given to.

Also see these links:

Метки

.net .NET C# .sort 1.2 2009 2010 404 error admin ajax amazon analytics and apache api archlinux asp.net async asynchronous autocomplete bash blender blog blogengine blogs book bootstrap bot bpython buildout byteflow bzr C c plus plus C++ cache cbv Chaco checkio chrome ci ckeditor class based views clojure closure cms cms с удобной админкой code coding style collectd COM comet competition conference ConfigParser contest Context continuous integration CouchDB coverage CppCMS cpyext cpython crud csrf CSS ctypes curl custom model fields cx_freeze cython database db dbm dbqueries debian debug debugging decorator decorators deploy deployment descriptor design dev devconf developers development diveintopython Django django 1.2 django 1.3 django advent django framework django template django trunk django weblog django-admin-tools django-cms django-compressor django-hosts django-piston django-registration django-sphinx django.admin djangoadvent djangocms djangodash doc documentation drupal e-legion eclipse EGit emacs encoding Enthought epoll erlang event exception ExtJS fabric facebook fastcgi finaloption fixtures fonts forms formset fp framework freebsd freeswitch fs2web ftp fun funcparserlib functional gae gamin gandi generic views gettext gevent gil git github gitosis Google Google App Engine google picasa Google Translate google wave Google Web Toolkit grab grablab greenlet gtd gui haskell hg hgshelve highlighter host hosting how-to howto html html5lib Hudson humor i18n icfpc ide idiomatic image-scripting improvements Internet interpreter ipython ironpython izmenimsya.ru jabber java javascript jenkins jetbrains JIT job jquery json jstree jython kde kiev kiyv kyivpy l10n ldap library libs Life Links linux Linux & Unix LLVM logging logs lxml Mac OS X magic mail markdown Matplotlib Mayavi maybe mediavirus meetup memcache Memcached memory messages metaclass middleware migration mikrotik mkd model models mod_python mod_wsgi mongodb monitoring mptt musicmans.ru musicx mvc my-projects mysql netCDF networkx newforms newforms-admin news nginx Nhibernate nix nose NoSQL numpy oop open source OpenID openoffice opster optimization oracle orm os pagination parsing path patterns pdf PDF-принтер PEP PEP8 performance performance optimization perl personality photo php picture-driven computing PIL pinax pingback pip plasma plone plugin plugins postgresql programming progress bar psycopg2 py2exe pybb pybbm pycamp pycharm pycon pycow pycurl pydev pygtk pylons PyNGL pypy pyqt PyQt4 pyrad pyramid PySide Python Python 2.5 python 2.7 python 3 python c api python speed python-mssql python3 pywinauto Qt Qt4 queue rabbitmq radius raw sql re redis redsolution redsolution cms regexp regular expressions release repoze.bfg RequestContext reusable apps robokassa rss ru ruby ruby-on-rails sample satchmo scalability SciPy scraping screencast search selenium self.error seo server setattr settings setuptools shell sikuli sms snippet socket.io software sorting south sphinx spider sql sqlalchemy sqlite ssh startup step-by-step subdomain subversion svn SyntaxHighlighter system tags tdd tddspry teh drama template templates templatetags test testing thinkpad threading threads tips tips and tricks tools tornadio tornado tornado server tricks tutorial tweepy twisted twitter typography uapycon Ubuntu ucsvlog uml Uncategorized unicode unit test unit testing UnitTest Unladen Swallow upload urllib urls utf-8 uwsgi validation vcs versioning video vim virtualenv Visual Studio vkontakte voip wave web web-devel web-services web-разработка webdev webfaction webkit webpy websockets webtest widget widgets Win API windows Wirbel work wrapper wsgi wxPython wxWidgets wysiwyg xapian xml xmonad xmpp xpath yandex youtube zip zomg zope [cdata[cbv]] [cdata[ci]] [cdata[class based views]] [cdata[continuous integration]] [cdata[django framework]] [cdata[django-sphinx]] [cdata[django]] [cdata[nginx]] [cdata[python]] [cdata[virtualenv]] [cdata[программирование]] автоматизация администрирование администрирование django админка алгоритмы архитектура атрибуты базы данных Без рубрики безопасность библиотеки блоге бот веб-разработка видео Визуализация данных вконтакте Все записи гвидо ван россум граббер графика графы декоратор декораторы дескриптор дескрипторы документация заметки игра жизнь идея интересное киев Клиентам книги конференция личное математика метаклассы модели модули монады морфология мысли невозможное новости о облачные вычисления обо мне Обработка данных оптимизация оптимизация кода Основная лента основы парсинг парсинг сайтов перевод песочница Питон поебень поиск правила кодирования программирование Проектирование производительность работа рабочее размышлизмы Разное разработка разработка приложений разработки регулярные выражения сайт событие события ссылки статьи тестирование тесты Тюмень убунтариум фигня философия формы форум Хабрахабр хакинг хостинг шаблоны шаблоны проектирования эксперимент Эксперименты юмор я пиарюсь Яндекс