本文介绍了测量时间在毫秒precision的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的计划是要相互比赛不同的排序算法,无论是在时间和空间。我有空间的覆盖,但测量时间是给我一些麻烦。下面是运行在各种code:

My program is going to race different sorting algorithms against each other, both in time and space. I've got space covered, but measuring time is giving me some trouble. Here is the code that runs the sorts:

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
  }
}

(我删除了一些为简单排序的交易算法)

(I removed some of the sorting algos for simplicity)

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

Now, I need to measure how much time the sorting algo takes. The most obvious way to do this is to record the time at point (a) and then subtract that from the time at point (b). But none of the C time functions are good enough:

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

time() gives me time in seconds, but the algos are faster than that, so I need something more accurate.

时钟()给我,因为该方案启动CPU蜱,但似乎舍入到最接近万张;还是不够小。

clock() gives me CPU ticks since the program started, but seems to round to the nearest 10,000; still not small enough

时间 shell命令工作得很好,但我需要运行每算法超过1000个测试,我需要为每一个单独的时间。

The time shell command works well enough, except that I need to run over 1,000 tests per algorithm, and I need the individual time for each one.

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

I have no idea what getrusage() returns, but it's also too long.

我需要的是在单位时间(显著,如果可能的话),比的排序功能的运行时间更小:约2毫秒。所以我的问题是:我在哪里可以得到的。

What I need is time in units (significantly, if possible) smaller than the run time of the sorting functions: about 2ms. So my question is: Where can I get that?

推荐答案

<$c$c>gettimeofday()具有微秒分辨率和易于使用。

gettimeofday() has microseconds resolution and is easy to use.

一对有用的定时器功能是:

A pair of useful timer functions is:

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);
}

这篇关于测量时间在毫秒precision的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 06:01