|
本帖最后由 Syylc120317 于 2015-4-15 19:39 编辑
自己解决的。
使用windows的api。
贴出代码,分享。
#include <windows.h>- /**
- * @author yuliuchuan
- * @date 2015-04-10
- * 查询程序占用内存。
- * 思路:通过调用外部命令'tasklist /FI "PID EQ pid"'。
- * 将返回的字符串首先替换掉',',
- * 然后用正则表达式匹配已KB为单位表示内存的字符串,
- * 最后换算为MB为单位返回。
- */
- QString PainterArea::getUsedMemory(DWORD pid)
- {
- char pidChar[25];
- //将DWORD类型转换为10进制的char*类型
- _ultoa(pid,pidChar,10);
- //调用外部命令
- QProcess p;
- p.start("tasklist /FI "PID EQ " + QString(pidChar) + " "");
- p.waitForFinished();
- //得到返回结果
- QString result = QString::fromLocal8Bit(p.readAllStandardOutput());
- //关闭外部命令
- p.close();
- //替换掉","
- result = result.replace(",","");
- //匹配 '数字+空格+K'部分。
- QRegExp rx("(\\d+)(\\s)(K)");
- //初始化结果
- QString usedMem("");
- if(rx.indexIn(result) != -1){
- //匹配成功
- usedMem = rx.cap(0);
- }
- //截取K前面的字符串,转换为数字,供换算单位使用。
- usedMem = usedMem.left(usedMem.length() - 1);
- //换算为MB的单位
- return QString::number(usedMem.toDouble() / 1024) + " MB";
- }
复制代码 使用的时候,getUsedMemory(GetCurrentProcessId());
GetCurrentProcessId()是windows的api。
|
|