Skip to content

Instantly share code, notes, and snippets.

@realies
Created April 11, 2023 18:42
Show Gist options
  • Save realies/59eb42231932a82453a3f05db0b62255 to your computer and use it in GitHub Desktop.
Save realies/59eb42231932a82453a3f05db0b62255 to your computer and use it in GitHub Desktop.
m1 mem speedtest
#include <iostream>
#include <chrono>
#include <cstdint>
#include <unistd.h> // for sysctl
const int64_t ARRAY_SIZE = 1024 * 1024 * 1024; // 1024 MB
const int64_t REPETITIONS = 1000;
inline void flush_cache() {
__builtin_arm_dsb(0b1111);
}
void measure_read_write_speed(int64_t* arr, int64_t size) {
if (arr == nullptr) {
std::cerr << "Invalid pointer" << std::endl;
return;
}
auto start = std::chrono::high_resolution_clock::now();
int64_t sum = 0;
for (int64_t i = 0; i < REPETITIONS; ++i) {
for (int64_t j = 0; j < size; ++j) {
arr[j] = arr[j] + 1;
sum += arr[j];
}
flush_cache();
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = end - start;
double time_per_operation = (elapsed.count() / (size * REPETITIONS)) * 1e9;
double read_speed = (sizeof(int64_t) * size * REPETITIONS) / elapsed.count() / 1e9;
double write_speed = (sizeof(int64_t) * size * REPETITIONS) / elapsed.count() / 1e9;
std::cout << "Memory latency: " << time_per_operation << " ns" << std::endl;
std::cout << "Read speed: " << read_speed << " GB/s" << std::endl;
std::cout << "Write speed: " << write_speed << " GB/s" << std::endl;
}
int main() {
int64_t* arr = new int64_t[ARRAY_SIZE];
// Check if allocation succeeded
if (arr == nullptr) {
std::cerr << "Failed to allocate memory" << std::endl;
return 1;
}
// Initialize array
for (int64_t i = 0; i < ARRAY_SIZE; ++i) {
arr[i] = i;
}
measure_read_write_speed(arr, ARRAY_SIZE);
delete[] arr;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment