量化交易之c++篇 - cache line对齐与不对齐的性能对比

#include <iostream>
#include <chrono>
#include <cstring>

using namespace std;

struct Data {
    uint64_t timestamp;     // 时间戳,8 字节
    double open_price;      // 开盘价,8 字节
    double close_price;     // 收盘价,8 字节
    double high_price;      // 最高价,8 字节
    double low_price;       // 最低价,8 字节
    char symbol[8];         // 股票代码,8 字节
    char exchange[8];       // 交易所代码,8 字节
};

struct AlignedData {
    uint64_t timestamp;     // 时间戳,8 字节
    double open_price;      // 开盘价,8 字节
    double close_price;     // 收盘价,8 字节
    double high_price;      // 最高价,8 字节
    double low_price;       // 最低价,8 字节
    char symbol[8];         // 股票代码,8 字节
    char exchange[8];       // 交易所代码,8 字节
} __attribute__((aligned(64)));   // cache line 对齐

int main() {
    Data data;
    AlignedData aligned_data;

    // 测量访问未对齐的数据结构的时间
    auto start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < 1000000; i++) {
        data.timestamp = i;
        data.open_price = i * 1.1;
        data.close_price = i * 1.2;
        data.high_price = i * 1.3;
        data.low_price = i * 1.4;
        std::strcpy(data.symbol, "AAPL");
        std::strcpy(data.exchange, "NASDAQ");
    }
    auto end = std::chrono::high_resolution_clock::now();
    std::cout << "Access unaligned data takes "
              << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()
              << " microseconds" << std::endl;

    // 测量访问对齐的数据结构的时间
    start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < 1000000; i++) {
        aligned_data.timestamp = i;
        aligned_data.open_price = i * 1.1;
        aligned_data.close_price = i * 1.2;
        aligned_data.high_price = i * 1.3;
        aligned_data.low_price = i * 1.4;
        std::strcpy(aligned_data.symbol, "AAPL");
        std::strcpy(aligned_data.exchange, "NASDAQ");
    }
    end = std::chrono::high_resolution_clock::now();
    std::cout << "Access aligned data takes " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << " microseconds" << std::endl;

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值