Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

Векторная обработка данных с использованием SIMD-команд. (C++) (таблицу строить не надо/…

  1. User

    Векторная обработка данных с использованием SIMD-команд. (C++) (таблицу строить не надо/ результаты выведи в консоль) Мы будем рассматривать интринсики над SSE инструкциями. F(x, y, z) = (x+y)/(x-y)+0.3z^2

    1. Составить программу применяющую функцию к входным массивам с получением на выходе массива вычисленных значений с применением инструкций векторной обработки данных SSE.
    2. Сравнить время вычисления функции и общее время работы с результатами без использования SSE.
    3. Оценить ускорение общего времени работы программы и непосредственно вычислений.
    4. Произвести эксперименты на массивах размером в 10 000 000, 50 000 000 и 100 000 000 элементов.
    5. Оценить объем памяти необходимый для размещения этих элементов в памяти.
    6. Результаты представить в виде таблицы представленной ниже.

    Показатель Кол-во элементов 10 000 000 50 000 000 100 000 000

    Объем занимаемой памяти, Кб Время вычисления без SSE, мс Время вычисления без SSE, мс Ускорение вычислений Общее время работы без SSE, мс Общее время работы c SSE, мс Общее ускорение

  2. Assistant
    #include <iostream>
    #include <immintrin.h>  // For SSE intrinsics
    #include <chrono>       // For timing
    #include <cmath>        // For math functions
    #include <cstdlib>
    
    void compute_non_sse(int N, const float* x, const float* y, const float* z, float* f)
    {
        for (int i = 0; i < N; ++i)
        {
            f[i] = (x[i] + y[i]) / (x[i] - y[i]) + 0.3f * z[i] * z[i];
        }
    }
    
    void compute_sse(int N, const float* x, const float* y, const float* z, float* f)
    {
        int i = 0;
        __m128 val_0_3 = _mm_set1_ps(0.3f);
        for (; i <= N - 4; i += 4)
        {
            __m128 x_vec = _mm_loadu_ps(&x[i]);
            __m128 y_vec = _mm_loadu_ps(&y[i]);
            __m128 z_vec = _mm_loadu_ps(&z[i]);
    
            __m128 x_plus_y = _mm_add_ps(x_vec, y_vec);
            __m128 x_minus_y = _mm_sub_ps(x_vec, y_vec);
            __m128 div_result = _mm_div_ps(x_plus_y, x_minus_y);
    
            __m128 z_squared = _mm_mul_ps(z_vec, z_vec);
            __m128 term2 = _mm_mul_ps(val_0_3, z_squared);
    
            __m128 result = _mm_add_ps(div_result, term2);
    
            _mm_storeu_ps(&f[i], result);
        }
    
        // Handle remaining elements
        for (; i < N; ++i)
        {
            f[i] = (x[i] + y[i]) / (x[i] - y[i]) + 0.3f * z[i] * z[i];
        }
    }
    
    int main()
    {
        int Ns[] = { 10'000'000, 50'000'000, 100'000'000 };
        for (int n_index = 0; n_index < 3; ++n_index)
        {
            int N = Ns[n_index];
            std::cout << "----------------------------------------" << std::endl;
            std::cout << "Число элементов: " << N << std::endl;
    
            // Measure total time without SSE
            auto total_start_non_sse = std::chrono::high_resolution_clock::now();
    
            // Allocate memory for x, y, z, f
            float* x = new float[N];
            float* y = new float[N];
            float* z = new float[N];
            float* f = new float[N];
    
            // Initialize x, y, z
            for (int i = 0; i < N; ++i)
            {
                x[i] = static_cast<float>(i + 1); // Avoid zero
                y[i] = static_cast<float>(i) / 2.0f + 0.1f; // Avoid x - y = 0
                z[i] = static_cast<float>(i % 1000) / 1000.0f;
            }
    
            // Measure computation time without SSE
            auto start_non_sse = std::chrono::high_resolution_clock::now();
            compute_non_sse(N, x, y, z, f);
            auto end_non_sse = std::chrono::high_resolution_clock::now();
            auto duration_non_sse = std::chrono::duration_cast<std::chrono::milliseconds>(end_non_sse - start_non_sse).count();
    
            auto total_end_non_sse = std::chrono::high_resolution_clock::now();
            auto total_duration_non_sse = std::chrono::duration_cast<std::chrono::milliseconds>(total_end_non_sse - total_start_non_sse).count();
    
            // Clean up
            delete[] x;
            delete[] y;
            delete[] z;
            delete[] f;
    
            // Measure total time with SSE
            auto total_start_sse = std::chrono::high_resolution_clock::now();
    
            // Allocate memory for x, y, z, f
            x = new float[N];
            y = new float[N];
            z = new float[N];
            f = new float[N];
    
            // Initialize x, y, z
            for (int i = 0; i < N; ++i)
            {
                x[i] = static_cast<float>(i + 1); // Avoid zero
                y[i] = static_cast<float>(i) / 2.0f + 0.1f; // Avoid x - y = 0
                z[i] = static_cast<float>(i % 1000) / 1000.0f;
            }
    
            // Measure computation time with SSE
            auto start_sse = std::chrono::high_resolution_clock::now();
            compute_sse(N, x, y, z, f);
            auto end_sse = std::chrono::high_resolution_clock::now();
            auto duration_sse = std::chrono::duration_cast<std::chrono::milliseconds>(end_sse - start_sse).count();
    
            auto total_end_sse = std::chrono::high_resolution_clock::now();
            auto total_duration_sse = std::chrono::duration_cast<std::chrono::milliseconds>(total_end_sse - total_start_sse).count();
    
            // Clean up
            delete[] x;
            delete[] y;
            delete[] z;
            delete[] f;
    
            // Calculate speedups
            double computation_speedup = static_cast<double>(duration_non_sse) / duration_sse;
            double total_speedup = static_cast<double>(total_duration_non_sse) / total_duration_sse;
    
            // Estimate memory usage
            double memory_usage_kb = static_cast<double>(N * sizeof(float) * 4) / 1024.0;
    
            // Output results
            std::cout << "Объем занимаемой памяти, Кб: " << memory_usage_kb << " KB" << std::endl;
            std::cout << "Время вычисления без SSE, мс: " << duration_non_sse << " ms" << std::endl;
            std::cout << "Время вычисления с SSE, мс: " << duration_sse << " ms" << std::endl;
            std::cout << "Ускорение вычислений: " << computation_speedup << std::endl;
            std::cout << "Общее время работы без SSE, мс: " << total_duration_non_sse << " ms" << std::endl;
            std::cout << "Общее время работы c SSE, мс: " << total_duration_sse << " ms" << std::endl;
            std::cout << "Общее ускорение: " << total_speedup << std::endl;
        }
    
        return 0;
    }
    

    Explanation:

    This C++ program performs vector data processing using SIMD instructions (SSE intrinsics) to apply the function ( F(x, y, z) = \frac{x + y}{x - y} + 0.3z^2 ) to large input arrays. It measures and compares the computation time and total runtime between the scalar (non-SSE) version and the SSE-optimized version.

    Here's what the program does:

    1. Function Implementation:

      • compute_non_sse(): Computes the function in a standard loop without using SSE instructions.
      • compute_sse(): Computes the function using SSE intrinsics to process four float elements simultaneously.
    2. Main Function:

      • Loops over array sizes of 10,000,000; 50,000,000; and 100,000,000 elements.
      • For each array size:
        • Allocates memory for the input arrays x, y, z, and the output array f.
        • Initializes the input arrays with values designed to avoid division by zero and to simulate variable data.
        • Measures the computation time and total runtime for both the non-SSE and SSE versions.
        • Calculates speedups by comparing the timings.
        • Outputs the memory usage and timing results to the console.
    3. Results Output:

      • The program prints the required metrics for each array size, including memory usage, computation times, speedups, and total runtimes.

    To Run the Program:

    • Ensure your compiler supports SSE intrinsics and the required headers (<immintrin.h>).
    • Compile the program with optimization flags to get accurate timing comparisons (e.g., -O2 or -O3 with GCC or Clang).
    • Run the executable, and it will output the results to the console.

    Note:

    • The program uses unaligned memory access (_mm_loadu_ps and _mm_storeu_ps) for simplicity. For potentially better performance, you could align memory allocations and use aligned load and store instructions.
    • The timings may vary depending on your system's hardware and current load.