我有一个C++应用程序,我想分析一下CPU、GPU和内存的使用情况。
所有这些信息都可以在macOS的监控应用程序中找到
现在,我正在通过一个shell命令获取此信息
const std::string getCPUCommand =
"ps -p " + std::to_string(pid) + " -o %cpu | awk 'FNR == 2 {print $1}'";
但这只获得CPU使用率,而不是GPU,而且这也是一个性能不高的命令。
有没有更好的方法来获取所有这些信息?
发布于 2021-08-30 04:22:07
关于CPU和内存使用率,这个问题已经在这个post中得到了回答。
简而言之-
交换/虚拟内存
#include <sys/param.h>
#include <sys/mount.h>
struct statfs stats;
if(statfs("/",&stats)==0)
FreeSwap=(unisgned long long)stats.f_bsize * stats.f_bfree;
xsw_usage
结构用于查找使用的总交换内存
xsw_usage used_swap={0};
unsigned int size=sizeof(used_swap);
随机存取存储器
当前使用的Ram -
#include <mach/vm_statistics.h>
#include <mach/mach_types.h>
#include <mach/mach_init.h>
#include <mach/mach_host.h>
int main(int argc, const char * argv[]) {
vm_size_t page_size;
mach_port_t mach_port;
mach_msg_type_number_t count;
vm_statistics64_data_t vm_stats;
mach_port = mach_host_self();
count = sizeof(vm_stats) / sizeof(natural_t);
if (KERN_SUCCESS == host_page_size(mach_port, &page_size) &&
KERN_SUCCESS == host_statistics64(mach_port, HOST_VM_INFO,
(host_info64_t)&vm_stats, &count))
{
long long free_memory = (int64_t)vm_stats.free_count * (int64_t)page_size;
long long used_memory = ((int64_t)vm_stats.active_count +
(int64_t)vm_stats.inactive_count +
(int64_t)vm_stats.wire_count) * (int64_t)page_size;
printf("free memory: %lld\nused memory: %lld\n", free_memory, used_memory);
}
return 0;
}
对于图形处理器的使用,你可以使用英伟达的Cuda Toolkit
特别是对于Mac -
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#include <cuda_runtime_api.h>
#define CUDA_CALL(function, ...) { \
cudaError_t status = function(__VA_ARGS__); \
anyCheck(status == cudaSuccess, cudaGetErrorString(status), #function, __FILE__, __LINE__); \
}
void anyCheck(bool is_ok, const char *description, const char *function, const char *file, int line) {
if (!is_ok) {
std::cout << "Error: " << description << " in " << function << " at " << file << ":" << line << std::endl;
exit(EXIT_FAILURE);
}
}
int main() {
int cudaDeviceCount;
struct cudaDeviceProp deviceProp;
size_t memFree, memTotal;
CUDA_CALL(cudaGetDeviceCount, &cudaDeviceCount);
for (int deviceId = 0; deviceId < cudaDeviceCount; ++deviceId) {
CUDA_CALL(cudaSetDevice, deviceId);
CUDA_CALL(cudaGetDeviceProperties, &deviceProp, deviceId);
//std::cout.imbue(std::locale("en_US.utf8"));
std::cout << "Device " << deviceId;
std::cout << " [PCIe " << deviceProp.pciDomainID << ":" << deviceProp.pciBusID
<< ":" << deviceProp.pciDeviceID << ".0]";
std::cout << ": " << deviceProp.name << " (CC " << deviceProp.major << "." << deviceProp.minor << ")";
CUDA_CALL(cudaMemGetInfo, &memFree, &memTotal);
std::cout << ": " << std::setprecision(5) << memFree/(1024*1024.)
<< " of " << memTotal/(1024*1024.) << " MB (i.e. "
<< std::setprecision(3) << 100*memFree/(float)memTotal << "%) Free"
<< std::endl;
}
return 0;
}
Ref-用于mac的cuda-smi
https://stackoverflow.com/questions/68977577
复制相似问题