【发布时间】:2020-02-02 19:26:28
【问题描述】:
我正在用 C 编写向量加法的代码。当我将参数传递为 1000 万时,我遇到了分段错误。
我知道当我们访问进程地址空间之外的内存地址时会发生分段错误。
但我不这么认为,这不是这里的原因。
我的代码是:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
struct timeval stop, start,start1,stop1;
void add(int a[], int b[],int N);
int main(int argc, char* argv[]){
gettimeofday(&start1, NULL);
if(argc<2){
printf("Please enter the value of N(number of elements)\n");
}else{
int i,N;
N=atoi(argv[1]);
N=N*1024;
int a[N],b[N];
for(i=0;i<=N;i++){
a[i]=rand()%1000;
b[i]=rand()%1000;
}
gettimeofday(&start, NULL);
add(a,b,N);
gettimeofday(&stop, NULL);
printf("took %lu us\n", (stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec - start.tv_usec);
}
gettimeofday(&stop1, NULL);
printf("Total took %lu us\n", (stop1.tv_sec - start1.tv_sec) * 1000000 + stop1.tv_usec - start1.tv_usec);
return 0;
}
void add(int a[], int b[], int N){
int c,i;
for(i=0;i<=N;i++){
c=a[i]+b[i];
// printf("%d + %d = %d\n",a[i],b[i],c);
}
}
输出如下:(命令参数为数组大小)
$ ./vectorAdd 1
took 9 us
Total took 233 us
$ ./vectorAdd 10
took 93 us
Total took 918 us
$ ./vectorAdd 100
took 210 us
Total took 4974 us
$ ./vectorAdd 1000
took 2371 us
Total took 20277 us
$ ./vectorAdd 10000
Segmentation fault (core dumped)
【问题讨论】:
-
在多任务系统上与其他进程和线程一起测量执行时间会给出不可靠的结果。对于基准测试,请执行您多次测量(数千次甚至数百万次)的任务并计算平均值或平均值。并记住始终衡量优化的构建。
-
你是如何编译你的代码的?如果它至少不是
-O2,那么您就是在浪费时间,因为 gcc 和大多数其他编译器默认生成的汇编器比次优的要差 -
另外,您在 add() 中有一个 printf,因此您正在测量输出到控制台的时间
-
for(i=0;i<=N;i++)导致数组溢出。这可能会导致崩溃。使用i < N; -
所有好的 cmets,但是,我怀疑您的分段错误是因为数组正在堆栈上分配。堆栈通常不是很大。
标签: c time segmentation-fault command-line-arguments