setuid, seteuid函数
几个有用的python函数 (笛卡尔积, 排列, 组合)

嵌套for循环优化: 次数少的放外面 && 变量少实例化 && 用++i

kitt posted @ 2014年1月14日 10:43 in 技术类 Tech , 1917 阅读

for (int i = 0; i < 20000; ++i)

    for (int j = 0; j < 2000; ++j)

        for (int k = 0; k < 200; ++k)

            testFunction(i, j, k);

怎么优化?

1. 循环次数少的放外面, 先200,再2000,再20000,分析见这篇文章

2. 减少循环变量实例化次数, 先int i,j,k; 再写循环语句

3. ++i比i++效率高,因为

      ++i;  // Fetch i, increment it, and return it

      i++;  // Fetch i, copy it, increment i, return copy

   对于int来说没什么差别, 如果i是object或iterator, 由于避免了copy操作, 效果比较明显。

 

测了一下, 1的效果明显, 2和3效果不明显, 编译器是g++

$ g++ --version

Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1

Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)

Target: x86_64-apple-darwin13.0.2

Thread model: posix

 

Avatar_small
依云 说:
2014年1月15日 01:30

2 和 3 不明显是因为现代编译器会优化。它们应该会生成一样的代码(至少在开启优化时)。

Avatar_small
kitt 说:
2014年1月15日 08:11

嗯, 现代的编译器真强大@依云:


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter