我正在使用 Dipperstein 的 bitarray.cpp 类来处理双层(黑白)图像,其中图像数据本身存储为一个像素一位。
我需要遍历每一位,每张图像大约 4--9 兆像素,超过数百张图像,使用 for 循环,例如:
for( int i = 0; i < imgLength; i++) {
if( myBitArray[i] == 1 ) {
// ... do stuff ...
}
}
性能是可用的,但并不惊人。我通过 gprof 运行程序,发现有大量时间和数百万次调用std::vector
迭代器和开始等方法。这是顶部采样的函数:
Flat profile:
Each sample counts as 0.01 seconds.
% cumulative self self total
time seconds seconds calls s/call s/call name
37.91 0.80 0.80 2 0.40 1.01 findPattern(bit_array_c*, bool*, int, int, int)
12.32 1.06 0.26 98375762 0.00 0.00 __gnu_cxx::__normal_iterator<unsigned char const*, std::vector<unsigned char, std::allocator<unsigned char> > >::__normal_iterator(unsigned char const* const&)
11.85 1.31 0.25 48183659 0.00 0.00 __gnu_cxx::__normal_iterator<unsigned char const*, std::vector<unsigned char, std::allocator<unsigned char> > >::operator+(int const&) const
11.37 1.55 0.24 49187881 0.00 0.00 std::vector<unsigned char, std::allocator<unsigned char> >::begin() const
9.24 1.75 0.20 48183659 0.00 0.00 bit_array_c::operator[](unsigned int) const
8.06 1.92 0.17 48183659 0.00 0.00 std::vector<unsigned char, std::allocator<unsigned char> >::operator[](unsigned int) const
5.21 2.02 0.11 48183659 0.00 0.00 __gnu_cxx::__normal_iterator<unsigned char const*, std::vector<unsigned char, std::allocator<unsigned char> > >::operator*() const
0.95 2.04 0.02 bit_array_c::operator()(unsigned int)
0.47 2.06 0.01 6025316 0.00 0.00 __gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char, std::allocator<unsigned char> > >::__normal_iterator(unsigned char* const&)
0.47 2.06 0.01 3012657 0.00 0.00 __gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char, std::allocator<unsigned char> > >::operator*() const
0.47 2.08 0.01 1004222 0.00 0.00 std::vector<unsigned char, std::allocator<unsigned char> >::end() const
... remainder omitted ...
我对 C++ 的 STL 不是很熟悉,但是谁能解释为什么 std::vector::begin() 被调用了几百万次?而且,当然,我是否可以做些什么来加快速度?
编辑:我只是放弃并优化了搜索功能(循环)。