C get cpu usage on linux and windows

十年热恋 提交于 2019-12-06 07:14:28

In the Linux version you've asked for RUSAGE_SELF, which is all threads of the parent process, rather than RUSAGE_CHILDREN for child processes. For IO usage under Linux you'll need a kernel after 2.6.20, and look in /proc/[pid]/io.

I think you have a similar problem on Windows. You'll need to use CreateProcess rather than system, so that you can get a handle to the child process and record its times. For IO usage on windows I think you'll need to use WMI, which is a large subject.

It is the correct output. ls is not the current process; whilst ls is executing, no CPU time is spent on your process.

BTW Dev-C++ is just a [bad, unmaintained] IDE, not a compiler. You probably meant to say MinGW.

You made a few errors in the linux version here.

  1. As Adrian pointed out, you should use RUSAGE_CHILDREN to count in the resource consumed by the child process.
  2. You did not call getrusage() again after you invoked system().
  3. In your printf(), you should not use %lf which represents a long double type. tv_sec is of type time_t and tv_usec is of type susecond_t. In 64-bit linux, they are both signed long, which is incompatible with long double (note you have negative result here). For portability, you should have used explicit cast, such as:

    printf("user time used: %ld  %ld\n",(long)p->ru_utime.tv_sec,(long)p->ru_utime.tv_usec);
    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!