for循环机制效率提示 [英] for-loop mechanism efficiency tips

查看:82
本文介绍了for循环机制效率提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在大型多维数组上使用for循环时,for循环机制本身的任何节省都是有意义的.

因此,我正在寻找有关如何减少这种开销的任何提示.

例如:使用uint而不是int和!= 0作为stop而不是> 0倒数,这会使CPU做更少的工作(听过一次,不确定是否总是如此)

解决方案

首先,不要流汗这些小东西.诸如递增计数或递减计数之类的细节通常与运行时间完全无关.众所周知,人类在发现需要加速的代码方面很糟糕.使用探查器.很少或根本不注意循环中没有重复的任何部分,除非事件探查器另有说明.请记住,在内部循环中编写的内容不一定在内部循环中执行,因为现代编译器非常聪明,可以避免不必要的重复.

话虽这么说,要非常警惕现代CPU上的展开循环.它们越紧密,就越适合缓存.在去年工作的高性能应用程序中,我使用循环代替了直线代码,并尽可能地加紧了它们,从而显着提高了性能. (是的,我进行了分析;有问题的函数占用了运行时间的80%.我还对典型输入的时间进行了基准测试,因此我知道所做的更改会有所帮助.)

此外,养成习惯于高效代码的习惯也没有害处.在C ++中,您应该养成使用前递增(++ i)而不是后递增(i ++)来递增循环变量的习惯.通常,这无关紧要,但是可以带来很大的不同,它不会使代码的可读性或可写性降低,并且不会受到损害.

As I am using for-loops on large multi-dim arrays, any saving on the for-loop mechanism itself is meaningful.

Accordingly, I am looking for any tips on how to reduce this overhead.

e.g. : counting down using uint instead of int and != 0 as stop instead of >0 allows the CPU to do less work (heard it once, not sure it is always true)

解决方案

First, don't sweat the small stuff. Details like counting up versus counting down are usually completely irrelevant in running time. Humans are notoriously bad at spotting areas in code that need to be sped up. Use a profiler. Pay little or no attention to any part of the loop that is not repeated, unless the profiler says otherwise. Remember that what is written in an inner loop is not necessarily executed in an inner loop, as modern compilers are pretty smart about avoiding unnecessary repetition.

That being said, be very wary of unrolling loops on modern CPUs. The tighter they are, the better they will fit into cache. In a high-performance application I worked on last year, I improved performance significantly by using loops instead of straight-line code, and tightening them up as much as I could. (Yes, I profiled; the function in question took up 80% of the run time. I also benchmarked times over typical input, so I knew the changes helped.)

Moreover, there's no harm in developing habits that favor efficient code. In C++, you should get in the habit of using pre-increment (++i) rather than post-increment (i++) to increment loop variables. It usually doesn't matter, but can make a significant difference, it doesn't make code less readable or writable, and won't hurt.

这篇关于for循环机制效率提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆