我注意到在过去的几天里,我的一些同学实际上已经尝试在 StackOverflow 上询问有关同一作业的问题,所以我将无耻地复制粘贴(仅)一个已删除(但仍被缓存)的问题的上下文在谷歌上没有答案)以节省时间。我为此提前道歉。
上下文
我正在尝试编写一个 C 程序来测量我系统的 L2 缓存的数据吞吐量 (MBytes/sec)。要执行测量,我必须编写一个程序,将数组 A 复制到数组 B,重复多次,然后测量吞吐量。
至少考虑两种情况:
- 两个字段都适合 L2 缓存
- 数组大小明显大于 L2 缓存大小。
使用 string.h 中的 memcpy() 复制数组,用一些值初始化两个数组(例如使用 rand() 的随机数),并重复至少 100 次,否则您看不到差异。
数组大小和重复次数应该是输入参数。其中一个数组大小应该是我的二级缓存大小的一半。
问题
因此,基于作业的上下文,我很清楚我需要做什么,因为它几乎直截了当地告诉了我。问题是我们得到了一些模板代码来使用,而我在破译其中的一部分时遇到了麻烦。如果有人能帮助我弄清楚发生了什么,我将不胜感激。
代码是:
/* do not add other includes */
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <string.h>
double getTime(){
  struct timeval t;
  double sec, msec;
  while (gettimeofday(&t, NULL) != 0);
  sec = t.tv_sec;
  msec = t.tv_usec;
  sec = sec + msec/1000000.0;
  return sec;
}
/* for task 1 only */
void usage(void)
{
    fprintf(stderr, "bandwith [--no_iterations iterations] [--array_size size]\n");
    exit(1);
}
int main (int argc, char *argv[])
{
  double t1, t2; 
  /* variables for task 1 */
  unsigned int size = 1024;
  unsigned int N = 100; 
  unsigned int i;
  /* declare variables; examples, adjust for task */
  int *A;
  int *B;
  /* parameter parsing task 1 */
  for(i=1; i<(unsigned)argc; i++) {
    if (strcmp(argv[i], "--no_iterations") == 0) {
      i++;
      if (i < argc)
        sscanf(argv[i], "%u", &N);
      else
        usage();
    } else if (strcmp(argv[i], "--array_size") == 0) {
      i++;
      if (i < argc)
        sscanf(argv[i], "%u", &size);
      else
        usage();
    } else usage();
  }
  /* allocate memory for arrays; examples, adjust for task */
  A = malloc (size*size * sizeof (int));
  B = malloc (size*size * sizeof (int));
  /* initialise arrray elements */    
  t1 = getTime();
  /* code to be measured goes here */
  t2 = getTime();
  /* output; examples, adjust for task */
  printf("time: %6.2f secs\n",t2 - t1);
  /* free memory; examples, adjust for task */
  free(B);
  free(A);
  return 0;  
}
我的问题是:
- 使用方法的目的是什么?
- 参数传递部分应该做什么,因为据我所知,它总是会导致使用()并且不会在 sscanf 行中使用任何参数?
- 在这个分配中,我们打算以 KB 或 MB 记录数组大小,我知道 malloc 以字节为单位分配大小,size变量值为 1024 将导致 1MB * sizeof(int) (我认为至少)。在这种情况下,我应该记录的数组大小是 1MB 还是 1MB * sizeof(int)?
- 如果参数传递工作正常并且我们传递参数来更改变size量值,那么数组大小是否总是size变量的平方?或者数组大小是否会被认为只是size变量?malloc size*size 而不是 size 似乎非常不直观,除非我对这一切都遗漏了一些东西。
- 我对测量吞吐量的理解是,我应该将数组大小乘以迭代次数,然后除以所用时间。我能得到任何确认这是正确的吗?
这些是我理解这项任务的唯一障碍。任何帮助将非常感激。