全部评论 5

  • 里面有点问题,也不知道看不看得出来

    5天前 来自 上海

    0
  • 666

    2025-07-13 来自 河北

    0
  • #include <iostream>
    #include <vector>
    #include <thread>
    #include <chrono>
    
    // 矩阵乘法函数
    void matrixMultiply(const std::vector<std::vector<int>>& A, 
                        const std::vector<std::vector<int>>& B, 
                        std::vector<std::vector<int>>& C, 
                        int startRow, int endRow) {
        int N = A.size();
        for (int i = startRow; i < endRow; ++i) {
            for (int j = 0; j < N; ++j) {
                C[i][j] = 0;
                for (int k = 0; k < N; ++k) {
                    C[i][j] += A[i][k] * B[k][j];
                }
            }
        }
    }
    
    int main() {
        int N = 1000; // 矩阵大小
        int numThreads = 4; // 线程数
    
        // 初始化矩阵
        std::vector<std::vector<int>> A(N, std::vector<int>(N, 1));
        std::vector<std::vector<int>> B(N, std::vector<int>(N, 1));
        std::vector<std::vector<int>> C(N, std::vector<int>(N, 0));
    
        // 记录开始时间
        auto start = std::chrono::high_resolution_clock::now();
    
        // 创建线程
        std::vector<std::thread> threads;
        int rowsPerThread = N / numThreads;
        for (int i = 0; i < numThreads; ++i) {
            int startRow = i * rowsPerThread;
            int endRow = (i == numThreads - 1) ? N : startRow + rowsPerThread;
            threads.emplace_back(matrixMultiply, std::ref(A), std::ref(B), std::ref(C), startRow, endRow);
        }
    
        // 等待所有线程完成
        for (auto& t : threads) {
            t.join();
        }
    
        // 记录结束时间
        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> duration = end - start;
    
        std::cout << "Matrix multiplication completed in " << duration.count() << " seconds." << std::endl;
    
        return 0;
    }
    
    

    2025-06-30 来自 安徽

    0
  • 连个return 0;都不写的,看着……不管了试试

    2025-06-28 来自 浙江

    0
  • 哦哦!我试试

    2025-06-28 来自 浙江

    0
首页