我有以下函数。
double single_channel_add(int patch_top_left_row, int patch_top_left_col,
int image_hash_key,
Mat* preloaded_images,
int* random_values){
int first_pixel_row = patch_top_left_row + random_values[0];
int first_pixel_col = patch_top_left_col + random_values[1];
int second_pixel_row = patch_top_left_row + random_values[2];
int second_pixel_col = patch_top_left_col + random_values[3];
int channel = random_values[4];
Vec3b* first_pixel_bgr = preloaded_images[image_hash_key].ptr<Vec3b>(first_pixel_row, first_pixel_col);
Vec3b* second_pixel_bgr = preloaded_images[image_hash_key].ptr<Vec3b>(second_pixel_row, second_pixel_col);
return (*first_pixel_bgr)[channel] + (*second_pixel_bgr)[channel];
}
这个程序中,patch_top_left_row
和patch_top_left_col
两个变量的值不断改变,大约被调用了一百五十万次。这个程序需要大约2秒运行完毕。当我将first_pixel_row
等变量从使用参数改为直接使用硬编码的数值时(如下所示),程序的运行时间快了很多,但我不知道原因。可能是编译器进行了某些优化(我在使用gcc交叉编译器)。
double single_channel_add(int patch_top_left_row, int patch_top_left_col,
int image_hash_key,
Mat* preloaded_images,
int* random_values){
int first_pixel_row = 5 + random_values[0];
int first_pixel_col = 6 + random_values[1];
int second_pixel_row = 8 + random_values[2];
int second_pixel_col = 10 + random_values[3];
int channel = random_values[4];
Vec3b* first_pixel_bgr = preloaded_images[image_hash_key].ptr<Vec3b>(first_pixel_row, first_pixel_col);
Vec3b* second_pixel_bgr = preloaded_images[image_hash_key].ptr<Vec3b>(second_pixel_row, second_pixel_col);
return (*first_pixel_bgr)[channel] + (*second_pixel_bgr)[channel];
}
编辑:
我已经粘贴了两个版本函数的汇编代码:
使用参数:http://pastebin.com/tpCi8c0F 使用常量:http://pastebin.com/bV0d7QH7编辑:
在使用-O3编译后,我得到了以下时钟周期和速度:
使用参数:1990000个时钟周期和1.99秒 使用常量:330000个时钟周期和0.33秒
编辑: 使用-03编译的参数:http://pastebin.com/fW2HCnHc 使用-03编译的常量:http://pastebin.com/FHs68Agi
gcc
有命令行选项可用于查看汇编输出。为什么不获取你在这里展示的两个代码片段的汇编代码,进行比较,并将结果差异发布在你的问题中呢? - Alex D