测量程序中使用的时间和内存 [英] measure time and memory used in program

查看:87
本文介绍了测量程序中使用的时间和内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨。

i有一个问题

我如何测量一个程序使用的时间和内存?

这意味着我想写一个程序,该程序使用12MB内存,该程序在1秒内完成。我想知道如何衡量这个节目的时间和记忆。

请帮助我。

非常感谢。

hi .
i have one question
how can i measure time and memory that one program used?
it means i want to write a program that this program use 12MB memory and this program excecute in 1 second. i want to know how i can measure time and memory of this program.
please help me.
thanks alot.

推荐答案

我至少可以回答关于处理时间的问题。



操作系统提供了获取进​​程花费时间的函数。但这些函数是特定于线程的。所以你必须得到每个线程的时间。这通常在线程终止时完成。



使用Windows,使用 GetThreadTimes()传递句柄线程。



使用Linux调用 clock_gettime()使用 CLOCK_THREAD_CPUTIME_ID 从线程内部。要获得总线程运行时间,请存储进程启动时的开始时间,以便稍后用于计算。



这里有一个Windows示例:

I can answer at least the question on the process times.

Operation systems provide functions to get the times a process has spend. But these functions are thread specific. So you must get the time for each thread. This is usually done when a thread will terminate.

With Windows, use GetThreadTimes() passing the handle of the thread.

With Linux call clock_gettime() with CLOCK_THREAD_CPUTIME_ID from within the thread. To get the total thread run time, store the start time when the process is started to use it later for the calculation.

Here an example for Windows:
void PrintThreadTimes(HANDLE hThread, LPCSTR lpszName)
{
    FILETIME ftCreate, ftExit, ftKernel, ftUser;
    SYSTEM_INFO si;
    ::GetSystemInfo(&si);
    if (::GetThreadTimes(hThread, &ftCreate, &ftExit, &ftKernel, &ftUser))
    {
        unsigned long long nCreate, nUser, nKernel, nExit;
        SYSTEMTIME st1, st2;
        DWORD dwExitCode;
        // ftExit is undefined when thread still running
        if (STILL_ACTIVE == ::GetExitCodeThread(hThread, &dwExitCode))
            ::GetSystemTimeAsFileTime(&ftExit);
        nUser = (ftUser.dwHighDateTime << 32ULL) + ftUser.dwLowDateTime;
        nKernel = (ftKernel.dwHighDateTime << 32ULL) + ftKernel.dwLowDateTime;
        nExit = (ftExit.dwHighDateTime << 32ULL) + ftExit.dwLowDateTime;
        nCreate = (ftCreate.dwHighDateTime << 32ULL) + ftCreate.dwLowDateTime;
        double fCpuUsage = 100.0 * (nKernel + nUser) / (nExit - nCreate);
        double fAvCpuUsage = fCpuUsage / si.dwNumberOfProcessors;
        ::FileTimeToSystemTime(&ftKernel, &st1);
        ::FileTimeToSystemTime(&ftUser, &st2);
        printf("%s thread times: kernel %02u:%02u:%02u.%03u, user %02u:%02u:%02u.%03u, CPU usage %.1f %%\n",
            lpszName, 
            st1.wHour, st1.wMinute, st1.wSecond, st1.wMilliseconds,
            st2.wHour, st2.wMinute, st2.wSecond, st2.wMilliseconds,
            fAvCpuUsage);
    }
}


这篇关于测量程序中使用的时间和内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆