当前位置:嗨网首页>书籍在线阅读

16-测试缓存

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

[toc]

3.4.6 测试缓存

RedisCache 类的源码可以在本书源码文件中的chp3文件夹中找到,其名为 rediscache.py 。和 DiskCache 一样,该缓存也可以在任何Python解释器中使用链接爬虫来进行测试。在这里,我们使用IPython,以便利用 %time 命令。

In [1]: from chp3.advanced_link_crawler import link_crawler
In [2]: from chp3.rediscache import RedisCache
In [3]: %time link_crawler('http://example.python-scraping.com/',
'/(index|view)', cache=RedisCache())
Downloading: http://example.python-scraping.com/
Downloading: http://example.python-scraping.com/index/1
Downloading: http://example.python-scraping.com/index/2
...
Downloading: http://example.python-scraping.com/view/Afghanistan-1
CPU times: user 352 ms, sys: 32 ms, total: 384 ms
Wall time: 1min 42s
In [4]: %time link_crawler('http://example.Python-scraping.com/',
'/(index|view)', cache=RedisCache())
Loaded from cache: http://example.python-scraping.com/
Loaded from cache: http://example.python-scraping.com/index/1
Loaded from cache: http://example.python-scraping.com/index/2
...
Loaded from cache: http://example.python-scraping.com/view/Afghanistan-1
CPU times: user 24 ms, sys: 8 ms, total: 32 ms
Wall time: 282 ms

在第一次迭代中,这里花费的时间与 DiskCache 基本相同。不过,Redis的速度在缓存加载时才能真正体现出来,与未压缩的磁盘缓存系统相比,有着超过3倍的速度增长。缓存代码可读性的增加,以及Redis集群在高可用性大数据解决方案上的扩展能力,则是锦上添花。