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 a vectorized version using SIMD intrinsics in C:
#include <xmmintrin.h> void vector_add(float *a, const float *b, int n) { int i = 0; // Vectorize 4 floats at a time for (; i < n-3; i+=4) { __m128 b_vec = _mm_loadu_ps(b+i); // load 4 floats from b b_vec = _mm_add_ps(b_vec, _mm_set1_ps(1.0f)); // add 1.0 to each element __m128 a_vec = _mm_loadu_ps(a+i); // load 4 floats from a a_vec = _mm_add_ps(a_vec, b_vec); // add _mm_storeu_ps(a+i, a_vec); // store results back to a } // Handle remaining elements for (; i < n; i++) { a[i] += b[i] + 1.0f; } }This uses SSE SIMD instructions to operate on 4 floats at a time. The key functions are:
- _mm_loadu_ps: Load 4 floats into a 128-bit SIMD register
- _mm_set1_ps: Set a SIMD register to a single float replicated 4 times
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.