我正在尝试测量我的内存的写入带宽,我创建了一个 8G char 数组,并使用 128 个线程在其上调用 memset。下面是代码片段。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <pthread.h>
int64_t char_num = 8000000000;
int threads = 128;
int res_num = 62500000;
uint8_t* arr;
static inline double timespec_to_sec(struct timespec t)
{
return t.tv_sec * 1.0 + t.tv_nsec / 1000000000.0;
}
void* multithread_memset(void* val) {
int thread_id = *(int*)val;
memset(arr + (res_num * thread_id), 1, res_num);
return NULL;
}
void start_parallel()
{
int* thread_id = malloc(sizeof(int) * threads);
for (int i = 0; i < threads; i++) {
thread_id[i] = i;
}
pthread_t* thread_array = malloc(sizeof(pthread_t) * threads);
for (int i = 0; i < threads; i++) {
pthread_create(&thread_array[i], NULL, multithread_memset, &thread_id[i]);
}
for (int i = 0; i < threads; i++) {
pthread_join(thread_array[i], NULL);
}
}
int main(int argc, char *argv[])
{
struct timespec before;
struct timespec after;
float time = 0;
arr = malloc(char_num);
clock_gettime(CLOCK_MONOTONIC, &before);
start_parallel();
clock_gettime(CLOCK_MONOTONIC, &after);
double before_time = timespec_to_sec(before);
double after_time = timespec_to_sec(after);
time = after_time - before_time;
printf("sequential = %10.8f\n", time);
return 0;
}
根据输出,完成所有 memset 需要 0.6 秒,据我了解,这意味着 8G/0.6 = 13G 内存写入带宽。但是,我有一个 2667 MHz DDR4,它应该有 21.3 GB/s 的带宽。我的代码或计算有什么问题吗?谢谢你的帮助!!