vectorize this piece of c code for me: for (int i = 0; i < 1024; i++) a[i] += b[i]+1.0f;
- User
vectorize this piece of c code for me:
for (int i = 0; i < 1024; i++) a[i] += b[i]+1.0f;
Assistant
Here is one way to vectorize that piece of C code:
#include <immintrin.h>
__m256 vsum = _mm256_set1_ps(1.0f);
for (int i = 0; i < 1024; i+=8) { __m256 va = _mm256_loadu_ps(a+i); __m256 vb = _mm256_loadu_ps(b+i);
va = _mm256_add_ps(va, _mm256_add_ps(vb, vsum)); _mm256_storeu_ps(a+i, va); }// Handle leftovers if size is not multiple of 8 for (int i = 1024-8; i < 1024; i++) { a[i] += b[i] + 1.0f; }
This uses AVX intrinsics to load/operate on 8 floats at a time using 256-bit wide vectors. It loads a chunk of a and b, adds 1.0f to b, then adds the results and stores back to a. The leftover elements at the end are handled with a scalar loop.
The key points are:
- Use 256-bit wide vector loads/stores
- Set 1.0f into a vector constant
- Add vectors element-wise
- Loop by 8 elements each iteration
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.