简单的内存延迟带宽读写带宽测试c++程序

#include <iostream>
#include <chrono>
#include <cstdlib>

int main(int argc, char *argv[]) {
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " <data_size_in_MB>\n";
        return 1;
    }

    // Get DATA_SIZE from command line argument
    size_t DATA_SIZE = std::atol(argv[1]) * 1024 * 1024;

    // Allocate memory space
    char* data = new char[DATA_SIZE];

    // Test memory read latency
    auto start = std::chrono::steady_clock::now();
    volatile char temp;
    for (size_t i = 0; i < DATA_SIZE; ++i) {
        temp = data[i];
    }
    auto end = std::chrono::steady_clock::now();
    std::chrono::duration<double> read_latency = end - start;

    // Test memory write latency
    start = std::chrono::steady_clock::now();
    for (size_t i = 0; i < DATA_SIZE; ++i) {
        data[i] = 0;
    }
    end = std::chrono::steady_clock::now();
    std::chrono::duration<double> write_latency = end - start;

    // Test memory read bandwidth
    start = std::chrono::steady_clock::now();
    for (size_t i = 0; i < DATA_SIZE; ++i) {
        temp = data[i];
    }
    end = std::chrono::steady_clock::now();
    std::chrono::duration<double> read_bandwidth_time = end - start;
    double read_bandwidth = (DATA_SIZE / read_bandwidth_time.count()) / (1024 * 1024); // in MB/s

    // Test memory write bandwidth
    start = std::chrono::steady_clock::now();
    for (size_t i = 0; i < DATA_SIZE; ++i) {
        data[i] = 0;
    }
    end = std::chrono::steady_clock::now();
    std::chrono::duration<double> write_bandwidth_time = end - start;
    double write_bandwidth = (DATA_SIZE / write_bandwidth_time.count()) / (1024 * 1024); // in MB/s

    // Output results
    std::cout << "Memory read latency: " << read_latency.count() << " seconds\n";
    std::cout << "Memory write latency: " << write_latency.count() << " seconds\n";
    std::cout << "Memory read bandwidth: " << read_bandwidth << " MB/s\n";
    std::cout << "Memory write bandwidth: " << write_bandwidth << " MB/s\n";

    // Free memory space
    delete[] data;

    return 0;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值