如何用C语言测量时间?

发布于 2024-09-16 03:05:05 字数 167 浏览 4 评论 0原文

我想知道某个代码块执行了多长时间(大约)。像这样:

startStopwatch();
// do some calculations
stopStopwatch();
printf("%lf", timeMesuredInSeconds);

怎么样?

I want to find out for how long (approximately) some block of code executes. Something like this:

startStopwatch();
// do some calculations
stopStopwatch();
printf("%lf", timeMesuredInSeconds);

How?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

时光暖心i 2024-09-23 03:05:05

中使用 clock 方法

您可以在 time.h示例 :

clock_t start = clock();
/*Do something*/
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;

You can use the clock method in time.h

Example:

clock_t start = clock();
/*Do something*/
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
走过海棠暮 2024-09-23 03:05:05

您可以使用 time.h 库,特别是 时间difftime 函数:(

/* difftime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t start,end;
  double dif;

  time (&start);
  // Do some calculation.
  time (&end);
  dif = difftime (end,start);
  printf ("Your calculations took %.2lf seconds to run.\n", dif );

  return 0;
}

改编自上面链接的 difftime 网页的示例。)

请注意,此方法只能给出秒级的精度 - time_t 记录自 UNIX 纪元(1970 年 1 月 1 日)以来的秒数。

You can use the time.h library, specifically the time and difftime functions:

/* difftime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t start,end;
  double dif;

  time (&start);
  // Do some calculation.
  time (&end);
  dif = difftime (end,start);
  printf ("Your calculations took %.2lf seconds to run.\n", dif );

  return 0;
}

(Example adapted from the difftime webpage linked above.)

Please note that this method can only give seconds worth of accuracy - time_t records the seconds since the UNIX epoch (Jan 1st, 1970).

久夏青 2024-09-23 03:05:05

有时需要测量天文时间而不是CPU时间(尤其适用于Linux):

#include <time.h>

double what_time_is_it()
{
    struct timespec now;
    clock_gettime(CLOCK_REALTIME, &now);
    return now.tv_sec + now.tv_nsec*1e-9;
}

int main() {
    double time = what_time_is_it();
    printf("time taken %.6lf\n", what_time_is_it() - time);
    return 0;
}

Sometime it's needed to measure astronomical time rather than CPU time (especially this applicable on Linux):

#include <time.h>

double what_time_is_it()
{
    struct timespec now;
    clock_gettime(CLOCK_REALTIME, &now);
    return now.tv_sec + now.tv_nsec*1e-9;
}

int main() {
    double time = what_time_is_it();
    printf("time taken %.6lf\n", what_time_is_it() - time);
    return 0;
}
冷清清 2024-09-23 03:05:05

标准 C 库提供了 time 函数,如果您只需要比较秒,则该函数非常有用。不过,如果您需要毫秒精度,最便携的方法是调用 timespec_get 。如果系统支持的话,它可以报出高达纳秒精度的时间。然而,调用它需要更多的努力,因为它涉及一个结构。下面的函数仅将结构转换为简单的 64 位整数。

#include <stdio.h>
#include <inttypes.h>
#include <time.h>

int64_t millis()
{
    struct timespec now;
    timespec_get(&now, TIME_UTC);
    return ((int64_t) now.tv_sec) * 1000 + ((int64_t) now.tv_nsec) / 1000000;
}

int main(void)
{
    printf("Unix timestamp with millisecond precision: %" PRId64 "\n", millis());
}

clock不同,此函数返回一个Unix时间戳,因此它将正确地考虑阻塞函数(例如sleep)所花费的时间。对于基准测试和实现考虑运行时间的延迟来说,这是一个有用的属性。

The standard C library provides the time function and it is useful if you only need to compare seconds. If you need millisecond precision, though, the most portable way is to call timespec_get. It can tell time up to nanosecond precision, if the system supports. Calling it, however, takes a bit more effort because it involves a struct. Here's a function that just converts the struct to a simple 64-bit integer.

#include <stdio.h>
#include <inttypes.h>
#include <time.h>

int64_t millis()
{
    struct timespec now;
    timespec_get(&now, TIME_UTC);
    return ((int64_t) now.tv_sec) * 1000 + ((int64_t) now.tv_nsec) / 1000000;
}

int main(void)
{
    printf("Unix timestamp with millisecond precision: %" PRId64 "\n", millis());
}

Unlike clock, this function returns a Unix timestamp so it will correctly account for the time spent in blocking functions, such as sleep. This is a useful property for benchmarking and implementing delays that take running time into account.

笑脸一如从前 2024-09-23 03:05:05

GetTickCount()。

#include <windows.h>
void MeasureIt()
{
    DWORD dwStartTime = GetTickCount();
    DWORD dwElapsed;

    DoSomethingThatYouWantToTime();

    dwElapsed = GetTickCount() - dwStartTime;

    printf("It took %d.%3d seconds to complete\n", dwElapsed/1000, dwElapsed - dwElapsed/1000);
}

GetTickCount().

#include <windows.h>
void MeasureIt()
{
    DWORD dwStartTime = GetTickCount();
    DWORD dwElapsed;

    DoSomethingThatYouWantToTime();

    dwElapsed = GetTickCount() - dwStartTime;

    printf("It took %d.%3d seconds to complete\n", dwElapsed/1000, dwElapsed - dwElapsed/1000);
}
空城仅有旧梦在 2024-09-23 03:05:05

为了完整起见,有比 GetTickCount()clock() 更精确的时钟计数器,它只提供 32 位结果,可以相对较快地溢出。它是 QueryPerformanceCounter()QueryPerformanceFrequency() 获取时钟频率,它是两个计数器差异的除数。类似中的CLOCKS_PER_SEC

#include <stdio.h>
#include <windows.h>

int main()
    {
    LARGE_INTEGER tu_freq, tu_start, tu_end;
    __int64 t_ns;

    QueryPerformanceFrequency(&tu_freq);
    QueryPerformanceCounter(&tu_start);
    /* do your stuff */
    QueryPerformanceCounter(&tu_end);

    t_ns = 1000000000ULL * (tu_end.QuadPart - tu_start.QuadPart) / tu_freq.QuadPart;
    printf("dt = %g[s]; (%llu)[ns]\n", t_ns/(double)1e+9, t_ns);

    return 0;
    }

For sake of completeness, there is more precise clock counter than GetTickCount() or clock() which gives you only 32-bit result that can overflow relatively quickly. It's QueryPerformanceCounter(). QueryPerformanceFrequency() gets clock frequency which is a divisor for two counters difference. Something like CLOCKS_PER_SEC in <time.h>.

#include <stdio.h>
#include <windows.h>

int main()
    {
    LARGE_INTEGER tu_freq, tu_start, tu_end;
    __int64 t_ns;

    QueryPerformanceFrequency(&tu_freq);
    QueryPerformanceCounter(&tu_start);
    /* do your stuff */
    QueryPerformanceCounter(&tu_end);

    t_ns = 1000000000ULL * (tu_end.QuadPart - tu_start.QuadPart) / tu_freq.QuadPart;
    printf("dt = %g[s]; (%llu)[ns]\n", t_ns/(double)1e+9, t_ns);

    return 0;
    }
∞觅青森が 2024-09-23 03:05:05

我会使用 QueryPerformanceCounterQueryPerformanceFrequency Windows API 函数。在块之前和之后调用前者并减去(当前 - 旧)以获得实例之间的“刻度”数。将其除以后一个函数获得的值即可得到持续时间(以秒为单位)。

I would use the QueryPerformanceCounter and QueryPerformanceFrequency functions of the Windows API. Call the former before and after the block and subtract (current − old) to get the number of "ticks" between the instances. Divide this by the value obtained by the latter function to get the duration in seconds.

相守太难 2024-09-23 03:05:05

如果您不需要出色的分辨率,可以使用 GetTickCount(): http://msdn.microsoft.com/en-us/library/ms724408(VS.85).aspx
(如果它不是为了您自己的简单诊断,那么请注意,这个数字可能会回绕,因此您需要用一些算术来处理它)。

QueryPerformanceCounter 是另一个合理的选择。 (MSDN上也有描述)

If you don't need fantastic resolution, you could use GetTickCount(): http://msdn.microsoft.com/en-us/library/ms724408(VS.85).aspx
(If it's for something other than your own simple diagnostics, then note that this number can wrap around, so you'll need to handle that with a little arithmetic).

QueryPerformanceCounter is another reasonable option. (It's also described on MSDN)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文