gpt4 book ai didi

c - 前 6 次迭代后出现段错误

转载 作者:行者123 更新时间:2023-11-30 18:46:44 27 4
gpt4 key购买 nike

我正在尝试测量以纳秒为单位的平均访问延迟,但在第一次迭代后我收到“段错误(核心转储)”。我错过了什么吗?我是否滥用了指针。这是导致错误的函数:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
#include <inttypes.h>

inline uint64_t as_nanoseconds(struct timespec* ts)
{
return ts->tv_sec * (uint64_t)1000000000L + ts->tv_nsec;
}

double measure(size_t sizes, uint32_t distance, size_t num_iter, size_t num_rep)
{
uint32_t *array;
array = malloc(sizes * sizeof(uint32_t));

int x = sizes / distance;

uint32_t *array_2;
array_2 = malloc(x * sizeof(uint32_t));

for (uint32_t i = 0; i < x; i++) {
array_2[i] = i;
}

for (size_t i = 0; i < sizes; i++) {
array[i] = 0;
}

for (size_t i = 0; i < x - 1; i++) {
array[array_2[i] * distance] = array_2[i + 1] * distance;
}

array[array_2[x - 1] * distance] = array_2[0] * distance;

double *measurements;
measurements = malloc(num_rep * sizeof(uint32_t));

uint64_t accu_nsec = 0;
struct timespec start;
struct timespec stop;

for (size_t run = 0; run < num_rep; ++run) {

volatile uint32_t next_offset = 0;

clock_gettime(CLOCK_REALTIME, &start);

for (size_t i = 0; i < num_iter / 1000; ++i) {
for (int x = 0; x < 1000; x++)
next_offset = array[next_offset];
}

clock_gettime(CLOCK_REALTIME, &stop);

accu_nsec += as_nanoseconds(&stop) - as_nanoseconds(&start);
double latency_per_access = (double)accu_nsec / num_iter;
measurements[run] = latency_per_access;
}

double AVG_LPA;

for (int i = 0; i < num_rep; i++)
AVG_LPA = +measurements[i];

return AVG_LPA / num_rep;
}

最佳答案

这里:

double *measurements;
measurements = malloc(num_rep * sizeof(uint32_t));

应该是

double *measurements;
measurements = malloc(num_rep * sizeof(double));

我也怀疑这个

double AVG_LPA;

for (int i = 0; i < num_rep; i++)
AVG_LPA = +measurements[i];

没有按照你的想法去做。也许

double AVG_LPA = 0.0;

for (int i = 0; i < num_rep; i++)
AVG_LPA += measurements[i];

关于c - 前 6 次迭代后出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50204536/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com