我用 C 语言实现了一个冒泡排序,并在测试其性能时发现该-O3标志使其运行速度甚至比没有标志时还要慢!与此同时-O2,它的运行速度比预期的要快得多。
没有优化:
time ./sort 30000
./sort 30000 1.82s user 0.00s system 99% cpu 1.816 total
Run Code Online (Sandbox Code Playgroud)
-O2:
time ./sort 30000
./sort 30000 1.00s user 0.00s system 99% cpu 1.005 total
Run Code Online (Sandbox Code Playgroud)
-O3:
time ./sort 30000
./sort 30000 2.01s user 0.00s system 99% cpu 2.007 total
Run Code Online (Sandbox Code Playgroud)
代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
int n;
void bubblesort(int *buf)
{
bool changed = true;
for (int i = n; changed == true; …Run Code Online (Sandbox Code Playgroud) 我正在查看为我的代码生成的程序集(使用Visual Studio 2017),并注意到_mm_load_ps经常(总是?)编译为movups.
我正在使用_mm_load_ps的数据定义如下:
struct alignas(16) Vector {
float v[4];
}
// often embedded in other structs like this
struct AABB {
Vector min;
Vector max;
bool intersection(/* parameters */) const;
}
Run Code Online (Sandbox Code Playgroud)
现在当我使用这个结构时,会发生以下情况:
// this code
__mm128 bb_min = _mm_load_ps(min.v);
// generates this
movups xmm4, XMMWORD PTR [r8]
Run Code Online (Sandbox Code Playgroud)
我期待movaps因为alignas(16).在这种情况下,我还需要其他东西来说服编译器使用movaps吗?
编辑:我的问题与这个问题不同,因为我没有遇到任何崩溃.结构是专门对齐的,我也使用对齐分配.相反,我很好奇为什么编译器将_mm_load_ps(对齐内存的固有内容)切换到movups.如果我知道struct是在一个对齐的地址分配的,我通过这个*调用它,那么使用movaps是安全的,对吧?