#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;
}
量化交易之c++篇 - cache line对齐与不对齐的性能对比
于 2023-04-23 13:36:08 首次发布