C语言中如何获取CPU使用率?

发布于 2024-12-21 06:25:13 字数 136 浏览 3 评论 0原文

我想获得 C 语言中应用程序的总 CPU 使用率,就像我们在 TaskManager 中获得的总 CPU 使用率... 我想知道...对于 windows 和 linux:: 当前所有进程的 CPU 总利用率 ..... 正如我们在任务管理器中看到的那样。

I want to get the overall total CPU usage for an application in C, the total CPU usage like we get in the TaskManager...
I want to know ... for windows and linux :: current Total CPU utilization by all processes ..... as we see in the task manager.

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

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

发布评论

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

评论(3

娇纵 2024-12-28 06:25:13

这是特定于平台的:

  • 在 Windows 中,您可以使用 GetProcessTimes() 函数。
  • 在 Linux 中,您实际上可以只使用 clock()

这些可用于测量两个时间间隔之间占用的 CPU 时间量。

编辑:

要获取 CPU 消耗(以百分比表示),您需要将总 CPU 时间除以操作系统看到的逻辑核心数量,然后除以总挂钟时间:

% CPU usage = (CPU time) / (# of cores) / (wall time)

获取逻辑核心的数量也是特定于平台的:

This is platform-specific:

  • In Windows, you can use the GetProcessTimes() function.
  • In Linux, you can actually just use clock().

These can be used to measure the amount of CPU time taken between two time intervals.

EDIT :

To get the CPU consumption (as a percentage), you will need to divide the total CPU time by the # of logical cores that the OS sees, and then divided by the total wall-clock time:

% CPU usage = (CPU time) / (# of cores) / (wall time)

Getting the # of logical cores is also platform-specific:

绅士风度i 2024-12-28 06:25:13

在 POSIX 下,您需要 getrusage(2) 的 ru_utime 字段。仅将 RUSAGE_SELF 用于调用进程,并将 RUSAGE_CHILDEN 用于所有已终止和 wait(2) 的子进程。 Linux 还仅支持调用线程的 RUSAGE_THREAD。如果您需要系统时间,请使用 ru_stime,系统时间可以与 ru_utime 相加,得出活动运行的总时间(不是挂机时间)。

Under POSIX, you want getrusage(2)'s ru_utime field. Use RUSAGE_SELF for just the calling process, and RUSAGE_CHILDEN for all terminated and wait(2)ed-upon children. Linux also supports RUSAGE_THREAD for just the calling thread. Use ru_stime if you want the system time, which can be summed with ru_utime for total time actively running (not wall time).

故事还在继续 2024-12-28 06:25:13

它通常是特定于操作系统的。

您可以使用 clock 函数,返回一个 clock_t(某些整数类型,例如long)。在 Linux 系统上,它以微秒为单位测量 CPU 时间。

It is usually operating system specific.

You could use the clock function, returning a clock_t (some integer type, like perhaps long). On Linux systems it measures the CPU time in microseconds.

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