C-交换两个相等大小的内存块的最快方法? [英] C - fastest method to swap two memory blocks of equal size?
问题描述
交换两个相等大小的不重叠内存区域的最快方法是什么?说,我需要将(t_Some *a)
与(t_Some *b)
交换.考虑到时空权衡,增加临时空间会提高速度吗?例如,(char *tmp)
vs (int *tmp)
?我正在寻找一种便携式解决方案.
What is the fastest way to swap two non-overlapping memory areas of equal size? Say, I need to swap (t_Some *a)
with (t_Some *b)
. Considering space-time trade-off, will increased temporary space improve the speed? For example, (char *tmp)
vs (int *tmp)
? I am looking for a portable solution.
原型:
void swap_elements_of_array(void* base, size_t size_of_element, int a, int b);
推荐答案
您最好的选择是最大化寄存器的使用率,这样,当您读取临时文件时,就不会获得额外的(可能是缓存的)内存访问.寄存器的数量将取决于系统,寄存器的分配(将变量映射到实际寄存器的逻辑)将取决于编译器.因此,您最好的选择是我估计只需要一个寄存器,并希望其大小与指针相同.归结为一个简单的for循环,用于处理解释为size_t
数组的块.
Your best bet is to maximize registers usage so that when you read a temporary you don't end up with extra (likely cached) memory accesses. Number of registers will depend on a system and registers allocation (the logic that maps your variables onto actual registers) will depend on a compiler. So your best bet is I guess to expect only one register and expect its size to be the same as the pointer. Which boils down to a simple for-loop dealing with blocks interpreted as arrays of size_t
.
这篇关于C-交换两个相等大小的内存块的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!