gpt4 book ai didi

c - Linux 中的执行时间不正确

转载 作者:行者123 更新时间:2023-11-30 20:18:43 25 4
gpt4 key购买 nike

对于那些将我的问题标记为已回答/重复的人:给定链接中的那些解决方案无法计算 Linux 中多线程程序中的 CPU 时间。

我正在使用以下代码来查找代码的执行时间。它在我的 Windows 10 机器上完美运行,但当涉及到 Linux 时,我得到的执行时间不正确(例如,实际执行时间不到 2 秒,但代码打印了 10 秒)。我已经尝试过 GCC 和 Intel 编译器,但仍然遇到同样的问题。知道出了什么问题吗?感谢您的时间和帮助。

clock_t begin;
clock_t end;
double time_spent;

begin = clock();
// run some calculations //
end = clock();
time_spent = ((double)(end - begin)) / CLOCKS_PER_SEC;
printf("Elapsed: %.12f \n\n", time_spent);

最佳答案

仔细阅读man页数 clock(3)time(7) (也许还有 clock_gettime(2) ,它可能用于实现 clock )。 clock文档说明:

The clock() function returns an approximation of processor time used by the program.

(强调的是我的)

也可使用time(1)测量程序的时间。

请注意clock函数正在测量CPU时间,而不是真正的挂钟时间。

实际上有传言说 on Windows, clock 错误测量真实的挂钟时间。但是standard clock function确实应该给处理器时间(检查 n1570 ,C11 标准,§7.27.2.1 了解更多)。

例如,如果您的长时间计算正在执行一些 I/O(通常是这种情况),它可能会等待磁盘(或等待到终端仿真器的输出,或来自用户的输入),并且那么CPU时间和真实的挂钟时间有很大不同。

I get incorrect execution time (for example the real execution time is less than 2 seconds but the code prints 10 seconds).

如果您的程序是多线程的,它的处理器时间(在多个内核上累积)可能会比实际的挂钟时间长。

I have tried both GCC and Intel compilers but still have the same issue.

clock功能由您的C standard library提供。标准<time.h> header 只是声明它。您的libc.so.6 ,可能来自GNU glibc (但您也可以尝试 musl-libc ),正在实现它。因此,您应该期望更改编译器不会改变 clock 的行为.

Any idea what is wrong?

也许您的期望是错误的(但如果没有 MCVE 我们无法确定)。

您还评论:

I was not able to find a simple way to get CPU time in my program.

然后考虑使用clock_gettime(2)与其中之一

   CLOCK_PROCESS_CPUTIME_ID (since Linux 2.6.12)
Per-process CPU-time clock (measures CPU time consumed by all
threads in the process).

CLOCK_THREAD_CPUTIME_ID (since Linux 2.6.12)
Thread-specific CPU-time clock.

关于c - Linux 中的执行时间不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53067918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com