C++获取内存使用情况

在程序编程过程中,为了防止出现内存泄漏情况出现,需要持续关注内存程序内存占用情况。如下方式实现获取当前进程内存使用情况:

linux:

void my_top(string path, bool flag)
{
    if(flag)
    {
        FILE* read_top = fopen("/proc/self/status", "r");
        char line_rss[128];
        unsigned long long Pid, VmSize, VmRSS;

        while (fgets(line_rss, 128, read_top) != NULL)
        {
            if (strncmp(line_rss, "Pid:", 4) == 0)
            {
                string str(line_rss + 4);
                Pid = strtoull(str.c_str(), NULL, 19);
            }

            if (strncmp(line_rss, "VmSize:", 7) == 0)
            {
                string str(line_rss + 7);
                VmSize = strtoull(str.c_str(), NULL, 19);
            }

            if (strncmp(line_rss, "VmRSS:", 6) == 0)
            {
                string str(line_rss + 6);
                VmRSS = strtoull(str.c_str(), NULL, 19);
            }

            if(Pid < 0 || VmSize < 0 || VmRSS < 0)
            {
                fclose(read_top);
                break;
            }
        }
        fclose(read_top);

        ofstream writer_top(path, ios::app);
        writer_top << Pid << " " << VmSize << " " << VmRSS << endl;
        writer_top.close();
    }
    else
    {
        ofstream writer_top(path, ios::app);
        writer_top << "0" << " " << "0" << " " << "0" << endl;
        writer_top.close();
    }
}

其他资源:

VmPeak: 	表示进程所占用最大虚拟内存大小
VmSize:     表示进程当前虚拟内存大小
VmLck:      表示被锁定的内存大小
VmHWM:    	表示进程所占用物理内存的峰值
VmRSS:     	表示进程当前占用物理内存的大小(与procrank中的RSS)
VmData:     表示进程数据段的大小
VmStk:      表示进程堆栈段的大小
VmExe:      表示进程代码的大小
VmLib:      表示进程所使用共享库的大小
VmPTE:      表示进程页表项的大小

windows:

#include <windows.h>
#include <psapi.h>
#include <stdio.h>

int main()
{
    PROCESS_MEMORY_COUNTERS pmc;
    if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)))
    {
        printf("当前进程占用内存大小为:%d KB\n", pmc.WorkingSetSize / 1024);
    }
    return 0;
}

另外可以通过如下方式获取文件的信息内容:

// 这是一个存储文件(夹)信息的结构体,其中有文件大小和创建时间、访问时间、修改时间等
struct stat statbuf;

// 提供文件名字符串,获得文件属性结构体
stat("path", &statbuf);

// 获取文件大小
size_t filesize = statbuf.st_size;

cout << filesize << endl;

ubuntu下获取文件创建或修改时间

 
// #include <fstream>
// #include <iostream>
// #include <sstream>
 
// #include "NvInfer.h"
// #include "NvOnnxParser.h"
// #include "NvInferRuntime.h"
 
// using namespace nvinfer1;
// using namespace nvonnxparser;
 
// // 全局创建 ILogger 类型的对象
// class Logger : public ILogger
// {
// 	virtual void log(Severity severity, const char* msg) noexcept override
// 	{
// 		// suppress info-level messages
// 		if (severity != Severity::kINFO)
// 			std::cout << msg << std::endl;
// 	}
// } gLogger;
 
// int onnx2engine(std::string onnx_filename, std::string enginefilePath, int type) {
 
 
// 	// 创建builder
// 	IBuilder* builder = createInferBuilder(gLogger);
 
// 	// 创建network
// 	nvinfer1::INetworkDefinition* network = builder->createNetworkV2(1U << static_cast<uint32_t>(NetworkDefinitionCreationFlag::kEXPLICIT_BATCH));
 
// 	// 创建onnx模型解析器
// 	auto parser = nvonnxparser::createParser(*network, gLogger);
 
// 	// 解析模型
// 	parser->parseFromFile(onnx_filename.c_str(), 2);
// 	for (int i = 0; i < parser->getNbErrors(); ++i)
// 	{
// 		std::cout << parser->getError(i)->desc() << std::endl;
// 	}
// 	printf("tensorRT load onnx model sucessful! \n"); // 解析模型成功,第一个断点测试
 
 
// 	// 使用builder对象构建engine
// 	IBuilderConfig* config = builder->createBuilderConfig();
// 	config->setMaxWorkspaceSize(16 * (1 << 20));  // 设置最大工作空间
// 	config->setFlag(BuilderFlag::kGPU_FALLBACK);  // 启用GPU回退模式,作用?
// 	//	config->setFlag(BuilderFlag::kSTRICT_TYPES);  //强制执行xx位的精度计算
// 	if (type == 1) {
// 		config->setFlag(nvinfer1::BuilderFlag::kFP16); // 设置精度计算
// 	}
// 	if (type == 2) {
// 		config->setFlag(nvinfer1::BuilderFlag::kINT8);
// 	}
 
// 	IOptimizationProfile* profile = builder->createOptimizationProfile(); //创建优化配置文件
// 	profile->setDimensions("images", OptProfileSelector::kMIN, Dims4(1, 3, 32, 300)); // 设置输入x的动态维度,最小值
// 	profile->setDimensions("images", OptProfileSelector::kOPT, Dims4(1, 3, 32, 320)); // 期望输入的最优值
// 	profile->setDimensions("images", OptProfileSelector::kMAX, Dims4(1, 3, 32, 340)); // 最大值
// 	config->addOptimizationProfile(profile);
 
 
// 	ICudaEngine* myengine = builder->buildEngineWithConfig(*network, *config); //创建engine  第二个断点测试
// 	std::cout << "try to save engine file now" << std::endl;
// 	std::ofstream p(enginefilePath, std::ios::binary);
// 	if (!p) {
// 		std::cerr << "could not open plan output file" << std::endl;
// 		return 0;
// 	}
 
// 	// 序列化
// 	IHostMemory* modelStream = myengine->serialize(); // 第三个断点测试
// 	p.write(reinterpret_cast<const char*>(modelStream->data()), modelStream->size()); // 写入
 
// 	modelStream->destroy(); // 销毁
// 	myengine->destroy();
// 	network->destroy();
// 	parser->destroy();
// 	std::cout << "convert onnx model to TensorRT engine model successfully!" << std::endl; // 转换成功,第四个断点测试
 
// 	return 0;
// }
 
// int main(int argc, char** argv) {
 
// 	onnx2engine("../data/best.onnx", "../data/best.engine", 1);
// 	return 0;
// }


#include <iostream>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <chrono>

int main() {
    const char* file_path = "filepath";
    struct stat file_stat;

    if (stat(file_path, &file_stat) == 0) 
	{
        // 获取文件的创建时间(秒数)
        time_t creation_time = file_stat.st_ctime;
        // 将时间转换为本地时间格式
        struct tm* local_time = localtime(&creation_time);
        // 打印创建时间
        std::cout << "文件的创建时间为: " << asctime(local_time);

		// 获取当前时间戳
		auto currentTime = std::chrono::system_clock::now();
		std::time_t t = std::chrono::system_clock::to_time_t(currentTime);
		int t_int = (int)t;
    } 
	else {
        std::cout << "无法获取文件信息" << std::endl;
    }

    return 0;
}

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值