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

06-缓存测试

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

[toc]

3.3.2 缓存测试

现在,我们通过向爬虫传递 cache 关键词参数,来检验 DiskCache 类。该类的完整源代码位于本书源码的chp3文件夹中,其名为 diskcache.py ,并且在任何Python解释器中均可以测试该缓存。

IPython是编写和解释Python的一套不错的工具,尤其是使用 `IPython magic commands` 进行Python调试时。你可以使用pip或conda安装 `IPython(pip install ipython)` 。

下面,我们使用IPython帮助我们对请求计时,以测试其性能。

In [1]: from chp3.diskcache import DiskCache
In [2]: from chp3.advanced_link_crawler import link_crawler
In [3]: %time link_crawler('http://example.python-scraping.com/',
'/(index|view)', cache=DiskCache())
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 300 ms, sys: 16 ms, total: 316 ms
Wall time: 1min 44s

第一次执行该命令时,由于缓存为空,因此网页会被正常下载。但当我们第二次执行该脚本时,网页加载自缓存中,爬虫应该更快完成执行,其执行结果如下所示。

In [4]: %time link_crawler('http://example.python-scraping.com/',
'/(index|view)', cache=DiskCache())
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 20 ms, sys: 0 ns, total: 20 ms
Wall time: 1.1 s

和上面的预期一样,爬取操作很快就完成了。当缓存为空时,我计算机中的爬虫下载耗时超过1分钟;而在第二次全部使用缓存时,该耗时只有1.1秒(比第一次爬取快了大约94倍!)。

由于硬件和网络连接速度的差异,在不同计算机中的准确执行时间也会有所区别。不过毋庸置疑的是,磁盘缓存比通过HTTP下载速度更快。