在 c++ 中交换 2D 双精度数组
我有以下方法在 C++ 中交换两个双精度数组 (double**)。对代码进行分析,该方法占运行时间的 7%...我在想这应该是一个低成本的操作,有什么建议吗?我是 C++ 新手,但我希望只交换对数组的引用。
62 void Solver::Swap(double** &v1, double** &v2)
63 {
64 double** vswap = NULL;
65 vswap = v2;
66 v2 = v1;
67 v1 = vswap;
68 }
I have the following method to swap two double arrays (double**) in c++. Profiling the code, the method is accounting for 7% of the runtime... I was thinking that this should be a low cost operation, any suggestions? I am new with c++, but i was hoping to just swap the references to the arrays.
62 void Solver::Swap(double** &v1, double** &v2)
63 {
64 double** vswap = NULL;
65 vswap = v2;
66 v2 = v1;
67 v1 = vswap;
68 }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
1)确保您的函数是内联的。
2) 您可以使用 XOR 来代替交换
3) 尝试强制编译器使用寄存器而不是堆栈来传递参数(即使 x86 上有很多寄存器压力,但值得尝试) - 您可以使用标准 < code>register 关键字或在 MS 编译器上使用
fastcall
。4) 不要为
vswap
等临时变量提供默认值。1) Make sure your function is inlined.
2) You can inplace swap, using a XOR for instance
3) Try to force the compiler to pass arguments using register instead of the stack (even though there's lot of register stress on x86, it's worth trying) - you can use the standard
register
keyword or play withfastcall
on MS' compiler.4) Don't bother giving default values for temporaries like
vswap
.代码看起来不错。它只是一个指针赋值。这取决于该方法被调用的次数。
The code looks fine. Its is just a pointer assignment. It depends on how many times the method was got called.
我猜你的探查器在这里有点困惑,因为这个方法实际上只交换两个指针,这是非常便宜的。除非此方法被多次调用,否则它不应显示在配置文件中。您的分析器是否告诉您此方法被调用的频率?
关于交换,您必须注意的一个问题是,一个数组可能在缓存中,而另一个数组则不在缓存中(特别是当它们很大时),因此不断交换指针可能会破坏缓存,但这会显示为一种普遍的缓慢行为。向下。
I guess your profiler is getting confused here a bit, as this method really only swaps two pointers, which is very cheap. Unless this method is called a lot, it shouldn't show up in a profile. Does your profiler tell you how often this method gets called?
One issue you have to be aware of with swapping is that one array might be in the cache and the other not (especially if they are large), so constantly swapping pointers might trash the cache, but this would show up as a general slow-down.
您确定您分析了完全优化的代码吗?
您应该
内联
此函数。除此之外,我看到的唯一一件事是您首先将
NULL
分配给vswap
,然后立即分配一些其他值 - 但这应该由优化器处理。但是,为什么不使用 std::swap() 呢?
Are you sure you profiled fully optimized code?
You should
inline
this function.Other than that the only thing I see is that you first assign
NULL
tovswap
and immediately afterwards some other value - but this should be taken care of by the optimizer.However, why don't you use
std::swap()
?不要假设 7% 意味着此操作很慢 - 这取决于其他正在发生的情况。
您可以让一个操作只需要 1 纳秒,并且无需执行任何其他操作,即可使其花费近 100% 的时间。
Don't assume that the 7% means this operation is slow - it depends on what else is going on.
You can have an operation that only takes 1 nanosecond, and make it take nearly 100% of the time, by doing nothing else.