本人在编写离线浏览器WebSeizer的过程中,用到大量字符串处理函数,这是很耗CPU的
一个处理过程,为了编写出高效率的网页解析引擎,对优化代码作了一番研究。
1 、高精度的计时函数
代码优化时需要用到精确的计时器。常用的有GetTickCount函数,可以达到毫秒级
的精度。但还是很不够的,这时可以采用提高循环次数的办法。另外,还有一个精度
更高的定时——“高分辨率性能计数器”(high-resolution performance counter),它提供了两个API
函数,取得计数器频率的QueryPerformanceFrequency和取得计数器数值
QueryPerformanceCounter。实现原理是利用计算机中的8253,8254可编程时间间隔定时器芯
片实现的。在计算机内部有三个独立的16位计数器。
计数器可以以二进制或二—十进制(BDC)计数。计数器每秒产生1193180次脉冲,每次
脉冲使计数器的数字减一,产生频率是可变的,用QueryPerformanceFrequency可以得到,一般
情况下都是1193180。QueryPerformance Counter可以得到当前的计数器值。所以只要你的计
算机够快,理论上精度可以达到1/1193180秒。
2 、代码优化实例
下面以一个自定义的字符串函数的为例,说明代码优化过程。
Delphi提供的字符串函数里有一个Pos函数,它的定义是:
function Pos(Substr: string; S: string): Integer;
它的作用是在字符串S中查找字符串Substr,返回值是Substr在S中第一次出现的位置,如果没有
找到,返回值为0。
在本人编写WebSeizer软件(天空软件站有下载)过程中,Pos已经不能满足要求。一方面:在
处理网页中的字符串时,要求对大小写不敏感,即