c - 调用 clock() 时出现段错误

标签 c linux performance

我正在尝试使用以下程序以编程方式了解缓存的效果。我的代码出现段错误。我使用了 GDB(使用 -g -O0 编译),发现它在

上出现段错误
start = clock() (first occourance)

我做错了什么吗?代码对我来说看起来不错。谁能指出错误?

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

#define MAX_SIZE (16*1024*1024)
int main()
{
    clock_t start, end;
    double cpu_time;
    int i = 0;
    int arr[MAX_SIZE];

    /* CPU clock ticks count start */
    start = clock();

    /* Loop 1 */
    for (i = 0; i < MAX_SIZE; i++) 
        arr[i] *= 3;

    /* CPU clock ticks count stop */
    end = clock();

    cpu_time = ((double) (end - start)) / CLOCKS_PER_SEC;

    printf("CPU time for loop 1 %.6f secs.\n", cpu_time);

    /* CPU clock ticks count start */
    start = clock();

    /* Loop 2 */
    for (i = 0; i < MAX_SIZE; i += 16) 
        arr[i] *= 3;

    /* CPU clock ticks count stop */
    end = clock();

    cpu_time = ((double) (end - start)) / CLOCKS_PER_SEC;

    printf("CPU time for loop 2 %.6f secs.\n", cpu_time);

    return 0;
}

最佳答案

数组对于堆栈来说可能太大了。尝试将其设置为 static ,以便它进入全局变量空间。作为额外的好处,static 变量被初始化为全零。

与其他类型的存储不同,编译器可以在编译时检查全局变量的资源是否存在(并且操作系统可以在程序启动前在运行时进行双重检查),因此您无需处理内存不足错误。未初始化的数组不会使您的可执行文件变大。

不幸的是,这是堆栈工作方式的一个粗略边缘。它位于固定大小的缓冲区中,由可执行程序的配置根据操作系统设置,但很少根据可用空间检查其实际大小。

欢迎来到 Stack Overflow 土地!

关于c - 调用 clock() 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17138250/

相关文章:

c++ - 标称情况优先与正 boolean 表达式

c - 函数指针赋值

c - 写入ini文件

linux - 在Linux中可靠写入

performance - Redis Twitter Clone 有N+1 Get?

c - C中读取多行多个数字(不指定数字的数量)

linux - 大量文件串联

linux - Bash 程序在 if 语句后挂起

sql - 索引空值以在 DB2 上快速搜索

performance - 我应该使用乘法还是除法?