c - 以毫秒精度测量时间

标签 c time

我的程序将在时间和空间上相互竞争不同的排序算法。我已经覆盖了空间,但是测量时间给我带来了一些麻烦。这是运行排序的代码:

void test(short* n, short len) {
  short i, j, a[1024];

  for(i=0; i<2; i++) {         // Loop over each sort algo
    memused = 0;               // Initialize memory marker
    for(j=0; j<len; j++)       // Copy scrambled list into fresh array
      a[j] = n[j];             // (Sorting algos are in-place)
                               // ***Point A***
    switch(i) {                // Pick sorting algo
    case 0:
      selectionSort(a, len);
    case 1:
      quicksort(a, len);
    }
                               // ***Point B***    
    spc[i][len] = memused;     // Record how much mem was used
  }
}

(为了简单起见,我删除了一些排序算法)

现在,我需要测量排序算法花费的时间。最明显的方法是记录 (a) 点的时间,然后从 (b) 点的时间中减去该时间。但是没有一个 C 时间函数足够好:

time() 给我时间(以秒为单位),但算法比这更快,所以我需要更准确的东西。

clock() 为我提供自程序启动以来的 CPU 滴答,但似乎四舍五入到最接近的 10,000;还是不够小

time shell 命令运行良好,除了我需要为每个算法运行超过 1,000 次测试,而且我需要每个测试单独的时间。

我不知道 getrusage() 返回什么,但它也太长了。

我需要的是比排序函数的运行时间短的单位时间(如果可能的话,显着):大约 2 毫秒。所以我的问题是:我在哪里可以买到它?

最佳答案

gettimeofday()具有微秒分辨率并且易于使用。

一对有用的定时器函数是:

static struct timeval tm1;

static inline void start()
{
    gettimeofday(&tm1, NULL);
}

static inline void stop()
{
    struct timeval tm2;
    gettimeofday(&tm2, NULL);

    unsigned long long t = 1000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec) / 1000;
    printf("%llu ms\n", t);
}

关于c - 以毫秒精度测量时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16764276/

相关文章:

c - 如何将数字读入 "subnumbers"?

css - 无法在 GTK3 中设置 "style property"

c++ - 同一字符串的多个#define是否使用相同的常量字符串?

javascript - html5中如何对输入时间采取步骤和限制?

android - android中的本地通知立即开始而不是在给定时间

Golang 按日期和时间查找最近的文件

c - 新程序员,我需要哈佛 CS50 提供的有关greedy.c的帮助

c++ - 是否定义了减去两个 NULL 指针的行为?

visual-studio - 我在 VS 项目上工作了多久?

c - 在 Windows 中使用 C 测量执行时间