ULARGE_INTEGER运算

在调用GetDiskFreeSpaceEx()获取磁盘空间时,由于参数是ULARGE_INTEGER(64位整数),所以普通的“加减乘除”并不支持(是没有实现),因此我们采用其他办法来实现,先来看下ULARGE_INTEGER的结构定义:

typedef union _ULARGE_INTEGER {  
  struct {  
    DWORD LowPart;  
    DWORD HighPart;  
  } ;  
  struct {  
    DWORD LowPart;  
    DWORD HighPart;  
  } u;  
  ULONGLONG QuadPart;  
} ULARGE_INTEGER, *PULARGE_INTEGER;  

在一次应用中,需要将返回的空间大小转换成以"GB"为单位的,所以写了这样的宏定义:

#define GB(x) ((x.HighPart << 2) + ((DWORD)x.LowPart) / 1024.0 / 1024.0 / 1024.0)

当然,你也可以选择将x两边加上括号即“#define GB(x) (((x).HighPart << 2) + ((DWORD)(x).LowPart) / 1024.0 / 1024.0 / 1024.0)"


下列是在OnInitDialog中编写的显示系统磁盘内存情况代码,修改代码通过按键实现所有磁盘内存单位切换成MB // 初始化列表控件 m_ListCtrl.InsertColumn(0, _T("软件名称"), LVCFMT_LEFT, 300); m_ListCtrl.InsertColumn(1, _T("版本号"), LVCFMT_LEFT, 300); m_ListCtrl.InsertColumn(2, _T("发布者"), LVCFMT_LEFT, 300); m_ListCtrl.InsertColumn(3, _T("安装路径"), LVCFMT_LEFT, 300); // 枚举注册表获取软件信息 EnumerateInstalledSoftware(); Clist2.InsertColumn(0, _T("盘符"), LVCFMT_LEFT, 200); Clist2.InsertColumn(1, _T("磁盘类型"), LVCFMT_LEFT, 200); Clist2.InsertColumn(2, _T("磁盘名称"), LVCFMT_LEFT, 200); Clist2.InsertColumn(3, _T("系统文件"), LVCFMT_LEFT, 200); Clist2.InsertColumn(4, _T("全部容量"), LVCFMT_LEFT, 200); Clist2.InsertColumn(5, _T("剩余容量"), LVCFMT_LEFT, 200); // 新列表 Clist3.InsertColumn(1, TEXT("C盘"), LVCFMT_LEFT,600); Clist3.InsertColumn(2, TEXT("D盘"), LVCFMT_LEFT,600); // 定义要处理的磁盘数组 CStringArray drives; drives.Add(_T("C:\\")); drives.Add(_T("D:\\")); for (int i = 0; i < drives.GetSize(); i++) { CString strDrive = drives[i]; // 获取磁盘类型 UINT nDiskType = GetDriveType(strDrive); CString strDiskType; switch (nDiskType) { case DRIVE_FIXED: strDiskType = _T("硬盘"); break; case DRIVE_REMOVABLE: strDiskType = _T("移动式磁盘"); break; case DRIVE_CDROM: strDiskType = _T("光驱"); break; case DRIVE_REMOTE: strDiskType = _T("网络磁盘"); break; case DRIVE_RAMDISK: strDiskType = _T("虚拟RAM磁盘"); break; case DRIVE_UNKNOWN: strDiskType = _T("未知设备"); break; default: strDiskType = _T("未知类型"); break; } // 获取磁盘名称和系统文件类型 TCHAR szVolumeName[MAX_PATH] = { 0 }; TCHAR szFileSystemName[MAX_PATH] = { 0 }; GetVolumeInformation(strDrive, szVolumeName, MAX_PATH, NULL, NULL, NULL, szFileSystemName, MAX_PATH); CString strVolumeName(szVolumeName); CString strFileSystemName(szFileSystemName); // 获取磁盘容量信息 ULARGE_INTEGER liTotalBytes, liFreeBytes; if (GetDiskFreeSpaceEx(strDrive, &liFreeBytes, &liTotalBytes, NULL)) { double dTotalGB = (double)liTotalBytes.QuadPart / (1024 * 1024 * 1024); double dFreeGB = (double)liFreeBytes.QuadPart / (1024 * 1024 * 1024); CString strTotalGB, strFreeGB; strTotalGB.Format(_T("%.2fGB"), dTotalGB); strFreeGB.Format(_T("%.2fGB"), dFreeGB); // 插入行 int nItem = Clist2.InsertItem(i, strDrive); Clist2.SetItemText(nItem, 1, strDiskType); Clist2.SetItemText(nItem, 2, strVolumeName); Clist2.SetItemText(nItem, 3, strFileSystemName); Clist2.SetItemText(nItem, 4, strTotalGB); Clist2.SetItemText(nItem, 5, strFreeGB); Clist3.InsertItem(0, TEXT("总容量:100GB")); Clist3.InsertItem(1, TEXT("可用容量:2GB")); Clist3.SetItemText(0, 1, strTotalGB); Clist3.SetItemText(1, 1, strFreeGB); } }
09-09
#include <iostream> #include <string> #include <chrono> #include <iomanip> #include <thread> #include <vector> #include <cmath> #include <fstream> #include <sstream> #include <cstdlib> #include <atomic> #include <mutex> #ifdef _WIN32 #include <windows.h> #include <psapi.h> #include <d3d11.h> #include <dxgi.h> #pragma comment(lib, "d3d11.lib") #pragma comment(lib, "dxgi.lib") #else #include <sys/sysinfo.h> #include <unistd.h> #endif using namespace std; // 系统资源监控结构体 struct SystemResources { double cpu_usage; double gpu_usage; long memory_used; long memory_total; long memory_available; }; // 全局变量用于线程控制 atomic<bool> running(true); mutex data_mutex; string current_pi_value = "3"; int current_precision = 0; // 高性能π计算算法 (Chudnovsky算法) class PiCalculator { private: // Chudnovsky算法常数 const double kC = 640320.0; const double kC3_24 = kC * kC * kC / 24.0; // 多精度计算参数 int precision; int terms; public: PiCalculator(int prec) : precision(prec) { // 根据所需精度计算需要的项数 terms = static_cast<int>(log10(kC3_24) * precision / 3) + 1; } int get_precision() const { return precision; } string calculate() { double sum = 0.0; double term; double factorial = 1.0; double sign = 1.0; // Chudnovsky算法实现 for (int k = 0; k < terms; ++k) { if (k > 0) { factorial *= (6.0 * k) * (6.0 * k - 1) * (6.0 * k - 2) * (6.0 * k - 3) * (6.0 * k - 4) * (6.0 * k - 5); factorial /= (3.0 * k) * (3.0 * k - 1) * (3.0 * k - 2) * pow(k, 3.0); sign *= -1; } term = (13591409.0 + 545140134.0 * k) * factorial; term *= sign; term /= pow(kC3_24, k + 0.5); sum += term; } double pi = 1.0 / (12.0 * sum); stringstream ss; ss << fixed << setprecision(precision) << pi; string result = ss.str(); // 确保格式正确,以3.开头 size_t dot_pos = result.find('.'); if (dot_pos != string::npos) { result = "3." + result.substr(dot_pos + 1); } else { result = "3.0"; } return result; } void update_precision(int new_precision) { precision = new_precision; terms = static_cast<int>(log10(kC3_24) * new_precision / 3) + 1; } }; #ifdef _WIN32 double get_gpu_usage() { return 0.0; // 简化处理 } #endif SystemResources get_system_resources() { SystemResources res{}; #ifdef _WIN32 // Windows CPU使用率计算 static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU; static int numProcessors = 0; static HANDLE self = GetCurrentProcess(); if (numProcessors == 0) { SYSTEM_INFO sysInfo; GetSystemInfo(&sysInfo); numProcessors = sysInfo.dwNumberOfProcessors; } FILETIME ftime, fsys, fuser; ULARGE_INTEGER now, sys, user; GetSystemTimeAsFileTime(&ftime); memcpy(&now, &ftime, sizeof(FILETIME)); GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser); memcpy(&sys, &fsys, sizeof(FILETIME)); memcpy(&user, &fuser, sizeof(FILETIME)); double percent = (sys.QuadPart - lastSysCPU.QuadPart) + (user.QuadPart - lastUserCPU.QuadPart); percent /= (now.QuadPart - lastCPU.QuadPart); percent /= numProcessors; res.cpu_usage = min(100.0, max(0.0, percent * 100)); lastCPU = now; lastUserCPU = user; lastSysCPU = sys; // 内存使用情况 MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); if (GlobalMemoryStatusEx(&memInfo)) { res.memory_total = memInfo.ullTotalPhys / (1024 * 1024); res.memory_available = memInfo.ullAvailPhys / (1024 * 1024); res.memory_used = res.memory_total - res.memory_available; } res.gpu_usage = get_gpu_usage(); #else // Linux CPU使用率计算 static unsigned long long lastTotalUser = 0, lastTotalUserLow = 0, lastTotalSys = 0, lastTotalIdle = 0; FILE* file = fopen("/proc/stat", "r"); if (file) { unsigned long long totalUser, totalUserLow, totalSys, totalIdle; if (fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow, &totalSys, &totalIdle) == 4) { if (lastTotalUser != 0) { unsigned long long total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) + (totalSys - lastTotalSys); unsigned long long totalIdleDiff = totalIdle - lastTotalIdle; unsigned long long totalUsed = total - totalIdleDiff; if (total > 0) { res.cpu_usage = (100.0 * totalUsed) / total; } } lastTotalUser = totalUser; lastTotalUserLow = totalUserLow; lastTotalSys = totalSys; lastTotalIdle = totalIdle; } fclose(file); } // Linux内存使用情况 struct sysinfo memInfo; if (sysinfo(&memInfo) == 0) { res.memory_total = memInfo.totalram * memInfo.mem_unit / (1024 * 1024); res.memory_available = memInfo.freeram * memInfo.mem_unit / (1024 * 1024); res.memory_used = res.memory_total - res.memory_available; } res.gpu_usage = 0.0; #endif return res; } void display_thread_func() { auto start_time = chrono::high_resolution_clock::now(); int iteration = 0; while (running) { iteration++; SystemResources res = get_system_resources(); string pi_value; int digits_calculated; { lock_guard<mutex> lock(data_mutex); pi_value = current_pi_value; digits_calculated = current_precision; } // 准备显示内容 stringstream display; display << "π: " << pi_value << "\n\n"; display << "CPU: " << fixed << setprecision(1) << res.cpu_usage << "%\n"; display << "GPU: " << fixed << setprecision(1) << res.gpu_usage << "%\n"; if (res.memory_total > 1024) { display << "内存: " << fixed << setprecision(1) << res.memory_used / 1024.0 << "GB/" << res.memory_total / 1024.0 << "GB (可用: " << res.memory_available / 1024.0 << "GB)\n"; } else { display << "内存: " << res.memory_used << "MB/" << res.memory_total << "MB (可用: " << res.memory_available << "MB)\n"; } display << "\n迭代次数: " << iteration << "\n"; auto current_time = chrono::high_resolution_clock::now(); double elapsed_seconds = chrono::duration_cast<chrono::duration<double>>(current_time - start_time).count(); double digits_per_second = digits_calculated / max(1.0, elapsed_seconds); display << "计算速度: " << fixed << setprecision(2) << digits_per_second << " 位/秒\n"; display << "已计算位数: " << digits_calculated << "\n"; system("clear || cls"); cout << display.str(); this_thread::sleep_for(chrono::milliseconds(500)); } } void calculation_thread_func() { PiCalculator calculator(2); // 初始精度 while (running) { string pi_value = calculator.calculate(); int precision = calculator.get_precision(); { lock_guard<mutex> lock(data_mutex); current_pi_value = pi_value; current_precision = precision; } // 逐步增加精度 int new_precision = min(precision * 2, 1000000); calculator.update_precision(new_precision); this_thread::sleep_for(chrono::milliseconds(100)); } } int main() { cout << "启动高性能π计算器..." << endl; cout << "使用Chudnovsky算法计算π" << endl; cout << "正在初始化..." << endl; this_thread::sleep_for(chrono::seconds(1)); try { thread display_thread(display_thread_func); thread calculation_thread(calculation_thread_func); cout << "按任意键停止计算..." << endl; cin.get(); running = false; display_thread.join(); calculation_thread.join(); cout << "\n计算已停止。" << endl; } catch (const exception& e) { cerr << "程序出错: " << e.what() << endl; return 1; } return 0; } 修改代码,使其可以正常的显示已计算的π位数和值,且可以正常的显示 CPU,内存 和 GPU 的使用率或占用大小,正确的使用内存,CPU 和 GPU,确保可以正常使用且可以打好配合 不在乎代码的工程量和长短,只追求完美的效果
07-25
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值