gpt4 book ai didi

c - gettimeofday() 上的奇怪标记

转载 作者:太空宇宙 更新时间:2023-11-04 06:47:33 28 4
gpt4 key购买 nike

我为我所在大学的抽样作业编写了这段代码。

#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char **argv){
struct timeval tv;

float t = atoi(argv[1]); //sampling time period in sec's
float dt = atoi(argv[2]); //sampling rate in msec's
double time;
int nsamples = t/dt * 1000; //number of samples floored

//samples storage array
double *samples;
samples = malloc(nsamples);

printf("%d\n\n",nsamples);

int c = 0; //array index
double divergance;

gettimeofday(&tv, NULL);
time =(double) tv.tv_sec + tv.tv_usec / 1000000.0f;
samples[c] = time;
printf("time: %f\n", samples[c]);

usleep(dt * 1000);

while(c<nsamples){
c++;

gettimeofday(&tv, NULL);
time = (double) tv.tv_sec + tv.tv_usec / 1000000.0f;
samples[c] = time;

//divergance calculated in msec's
divergance = (samples[c] - samples[c-1]);
if (c==9){
printf("%f \n \n%f", samples[c-1], samples[c]);
}
printf("time: %f\ndivergance: %f ms\n\n", samples[c], divergance*1000);

usleep(dt *1000);
}

}

这是我的输出

time: 1557335682.435666 divergance: 200.127125 ms

time: 1557335682.635813 divergance: 200.146914 ms

time: 1557335682.835952 divergance: 200.139046 ms

time: 1557335683.036075 divergance: 200.123072 ms

time: 1557335683.236192 divergance: -50328976507548121002151598324465532616014103321089770750300716493231241208217866953937760599346823570331739493744117764925654540012842402655523878795775819489233146901362588461216017208320541658368563434403808909221817741213696.000000 ms

time: 1557335683.436400 divergance: 1557335683436.399902 ms

time: 1557335683.636521 divergance: 1557335683636.520752 ms

time: 1557335683.836647 divergance: 1557335683836.646973 ms

有谁知道第五次计算的奇怪输出是什么?我无法想象任何合乎逻辑的解释,因为我以前没有遇到过任何类似的“错误”。它是否与 gettimeofday() 函数的某些特定功能有关?

注意:输入是 10200

最佳答案

您没有为样本分配足够的空间:

samples = malloc(nsamples);

malloc 函数为指定数量的字节 分配空间,而不是数组元素的数量。所以你的数组比你想象的要短得多。这意味着你最终会写到数组的末尾,调用 undefined behavior .

您需要将元素数量乘以元素大小才能分配正确的空间量:

samples = malloc(nsamples * sizeof(*samples));

你在访问数组时也有一个差一个错误:

int c = 0;
...
while(c<nsamples){
c++;
...
samples[c] = time;
...
}

这也会写到数组末尾,特别是一个数组元素太多了。

将循环更改为从值 1 开始并在结束时递增。

int c = 0;
...
c = 1;
while(c<nsamples){
...
samples[c] = time;
...
c++;
}

关于c - gettimeofday() 上的奇怪标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56046095/

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