快速生成N*N的随机矩阵

实测单线程生成10000*10000的随机数矩阵只要2s

核心思想在于将二维矩阵转化为一维数组进行操作

编译:g++ -std=c++11 randomMaker.cpp -o randomMaker
运行:./randomMaker <dimension>

randomMaker.cpp:

#include <cstdlib>
#include <algorithm>
#include <cassert>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
#include <sys/time.h>

namespace utils {
    int N;

    void abort_with_error_message(std::string msg) {
        std::cerr << msg << std::endl;
        abort();
    }
    
    int convert_dimension_2D_1D(int x, int y, int n) {
        return x * n + y;
    }

    int print_result(int *mat) {
        std::ofstream outputf("out.txt", std::ofstream::out);

        for (int i = 0; i < N*N; i++)
            outputf << mat[i] << " \n"[(i+1)%N==0];

        outputf.flush();
        outputf.close();
        return 0;
    }
} //namespace utils

void make_randomMat(int N, int *mat, int Maxnum) {
    for (int i = 0; i < N; i ++) 
        for (int j = 0; j < N; j ++)
            mat[utils::convert_dimension_2D_1D(i, j, N)] = rand() % Maxnum;
}

int main(int argc, char *argv[]) {
    if (argc <= 1) {
        utils::abort_with_error_message("NUMBER OF DIMENSION WAS NOT FOUND!");
    }

    int dim = atoi(argv[1]);

    // matrix should be smaller than 20MB * 20MB (400MB, we don't have too much memory for multi-processors)
    assert(dim < (1024 * 1024 * 20));
    utils::N = dim;

    int *mat;
    mat = (int *)malloc(sizeof(int) * dim * dim);

    freopen("out.txt", "w", stdout);
    srand((unsigned)time(0));

    timeval start_wall_time_t, end_wall_time_t;
    float ms_wall;

    //start timer
    gettimeofday(&start_wall_time_t, nullptr);

    make_randomMat(dim, mat, 1000000);

    //end timer
    gettimeofday(&end_wall_time_t, nullptr);
    ms_wall = ((end_wall_time_t.tv_sec - start_wall_time_t.tv_sec) * 1000 * 1000 + end_wall_time_t.tv_usec - start_wall_time_t.tv_usec) / 1000.0;

    std::cerr.setf(std::ios::fixed);
    std::cerr << std::setprecision(6) << "Time(s): " << (ms_wall / 1000.0) << std::endl;
    utils::print_result(mat);

    free(mat);
    return 0;
}

发布了673 篇原创文章 · 获赞 644 · 访问量 38万+

猜你喜欢

转载自blog.csdn.net/zhaohaibo_/article/details/102600552
今日推荐