1

I want to log the CPU usage of my C program in Visual Studio. Using Performance Profile I am able to view the graphical representation of the CPU usage of my C program. But what should I do or what code should I add to my existing code so that I can log the CPU usage of my program for each second in a text or an excel file.

  • Possible duplicate of [How to determine CPU and memory consumption from inside a process?](https://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process) – weeska Jun 30 '17 at 06:58
  • My question is how to log the cpu usage in an excel or text file..and not just view it @weeska –  Jun 30 '17 at 07:04
  • A I see - that wasn't clear to me. Sorry – weeska Jun 30 '17 at 09:33

1 Answers1

2

Probably the easiest thing to do would be to create a thread, that just uses GetProcessTimes to get the process' current CPU usage, write it out to the file, sleep a second, and repeat. You can then (for example) set a signal to tell it to exit:

FILETIME creation, done, kernel, user;
int PID;

std::atomic<bool> finished = false;

std::thread logger([&] {
    printf("seconds\n");
    while (!finished) {
        GetProcessTimes(GetCurrentProcess(), &creation, &done, &kernel, &user);

        SYSTEMTIME used_k, used_u;

        FileTimeToSystemTime(&kernel, &used_k);
        FileTimeToSystemTime(&user, &used_u);

        DWORD milliseconds = used_k.wMilliseconds + used_u.wMilliseconds;
        DWORD seconds = used_k.wSecond + used_u.wSecond;

        printf("%d.%3.3d\n", seconds, milliseconds);
        Sleep(1000);
    }
});

// Do work to be timed/logged here

finished = true;
logger.join();
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • ok.. i somehow was able to get the cpu usage of my program every second. but when i added the code such that the console output may be written onto a csv file, the program throws me an exception saying that there is some integer diviion by zero.. what should i do? @Jerry Coffin –  Jun 30 '17 at 11:10
  • 1
    @JessieBunny: My crystal ball tells me the error is on line 42. Seriously: I can't really diagnose your code based on that description. I suppose what you should do is debug your code. – Jerry Coffin Jun 30 '17 at 13:09