cache

Содержание
Введение
Пример
Похожие статьи

Введение

С помощью кэширования можно создавать функции, которые сохраняют своё состояние (maintain state).

Благодаря этому можно увеличить производительность программ.

gethostbyname()

Рассмотрим функцию gethostbyname() из статьи про сокеты

import socket def main(): print(resolve) ip = resolve("www.eth1.ru") print(ip) def resolve(host): return socket.gethostbyname(host) if __name__ == "__main__": main()

Рассмотрим скрипт resolver.py , в котором реализован тот же функционал, плюс добавлено кэширование

import socket class Resolver: def __init__(self): self._cache = {} # __call__ делает возможным вызвать объект def __call__(self, host): if host not in self._cache: self._cache[host] = socket.gethostname(host) return self._cache[host]

python from resolver import Resolver resolve = Resolver() resolve('heihei.ru')

'87.236.16.134'

>>> resolve.__call__('heihei.ru') '87.236.16.134' >>> resolve._cache {'heihei.ru': '87.236.16.134'} >>> resolve('beget.com') '193.168.47.254' >>> resolve._cache {'heihei.ru': '87.236.16.134', 'beget.com': '193.168.47.254'} >>> from timeit import timeit >>> timeit(setup="from __main__ import resolve", stmt="resolve('google.com')", number=1) 0.011513292000017827 >>> timeit(setup="from __main__ import resolve", stmt="resolve('google.com')", number=1) 1.116900057240855e-05 >>> print("{:f}".format(_)) 0.000011

Добавим функционал

import socket class Resolver: def __init__(self): self._cache = {} def __call__(self, host): if host not in self._cache: self._cache[host] = socket.gethostbyname(host) return self._cache[host] def clear(self): self._cache.clear() def has_host(self, host): return host in self._cache

python >>> from resolver import Resolver >>> resolve = Resolver() >>> resolve.has_host("topbicycle.ru")

False

>>> resolve("topbicycle.ru") '87.236.16.134' >>> resolve.has_host("topbicycle.ru") True >>> resolve.clear() >>> resolve.has_host("topbicycle.ru") False

Article author: Andrei Olegovich

Похожие статьи
Функции
Python
*args **kwargs
sys.argv: аргументы командной строки
Лямбда функции
Функции первого класса
Замыкания
Декораторы
if, elif, else
Циклы
Методы
Итерация
Генераторы
Генераторы: Maintaining State
Встроенные фукнции: all() … zip()

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: