From fe1e2f16ff61ceaaca65f52590a5d5a4b132d790 Mon Sep 17 00:00:00 2001 From: Aldo Cortesi Date: Tue, 15 Mar 2011 13:05:33 +1300 Subject: Improve responsiveness of request and response viewing. - Computing the view of a large body is expensive, so we introduce an LRU cache to hold the latest 20 results. - Use ListView more correctly, passing it individual urwid.Text snippets, rather than a single large one. This hugely improves render time. --- libmproxy/utils.py | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) (limited to 'libmproxy/utils.py') diff --git a/libmproxy/utils.py b/libmproxy/utils.py index a64eca4e..34c49e14 100644 --- a/libmproxy/utils.py +++ b/libmproxy/utils.py @@ -12,7 +12,7 @@ # # You should have received a copy of the GNU General Public License # along with this program. If not, see . -import re, os, subprocess, datetime, textwrap, errno, sys, time +import re, os, subprocess, datetime, textwrap, errno, sys, time, functools def timestamp(): @@ -444,3 +444,41 @@ def dummy_cert(certdir, ca, commonname): ) if ret: return None return certpath + + +class LRUCache: + """ + A decorator that implements a self-expiring LRU cache for class + methods (not functions!). + + Cache data is tracked as attributes on the object itself. There is + therefore a separate cache for each object instance. + """ + def __init__(self, size=100): + self.size = size + + def __call__(self, f): + cacheName = "_cached_%s"%f.__name__ + cacheListName = "_cachelist_%s"%f.__name__ + size = self.size + + @functools.wraps(f) + def wrap(self, *args): + if not hasattr(self, cacheName): + setattr(self, cacheName, {}) + setattr(self, cacheListName, []) + cache = getattr(self, cacheName) + cacheList = getattr(self, cacheListName) + if cache.has_key(args): + cacheList.remove(args) + cacheList.insert(0, args) + return cache[args] + else: + ret = f(self, *args) + cacheList.insert(0, args) + cache[args] = ret + if len(cacheList) > size: + d = cacheList.pop() + cache.pop(d) + return ret + return wrap -- cgit v1.2.3