news 2026/5/30 22:10:03

C++电脑性能测试代码

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
C++电脑性能测试代码

源代码,拷贝到编译器上运行即可

#include <iostream> #include <vector> #include <chrono> #include <cmath> #include <algorithm> #include <random> #include <fstream> #include <iomanip> #include <cstring> #include <functional> #include <numeric> #ifdef _WIN32 #include <windows.h> #include <psapi.h> #elif defined(__linux__) #include <unistd.h> #include <sys/sysinfo.h> #elif defined(__APPLE__) #include <sys/types.h> #include <sys/sysctl.h> #endif class SystemInfo { public: static int getCPUThreads() { // 使用平台特定方法获取CPU核心数 #ifdef _WIN32 SYSTEM_INFO sysInfo; GetSystemInfo(&sysInfo); return sysInfo.dwNumberOfProcessors; #elif defined(__linux__) return sysconf(_SC_NPROCESSORS_ONLN); #elif defined(__APPLE__) int numCPU; size_t len = sizeof(numCPU); sysctlbyname("hw.ncpu", &numCPU, &len, NULL, 0); return numCPU; #else return 1; // 默认值 #endif } static double getMemoryGB() { #ifdef _WIN32 MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); GlobalMemoryStatusEx(&memInfo); return memInfo.ullTotalPhys / (1024.0 * 1024 * 1024); #elif defined(__linux__) struct sysinfo memInfo; sysinfo(&memInfo); return memInfo.totalram * memInfo.mem_unit / (1024.0 * 1024 * 1024); #elif defined(__APPLE__) int64_t memSize; size_t length = sizeof(memSize); sysctlbyname("hw.memsize", &memSize, &length, NULL, 0); return memSize / (1024.0 * 1024 * 1024); #endif return 0; } }; class Benchmark { private: struct TestResult { std::string name; double score; double weight; double rawValue; std::string unit; }; std::vector<TestResult> results; double normalizeScore(double value, double min, double max, bool higherBetter = true) { if (value < min) return 0.0; if (value > max) return 100.0; if (higherBetter) { return ((value - min) / (max - min)) * 100.0; } else { return ((max - value) / (max - min)) * 100.0; } } public: // CPU性能测试 - 浮点运算 TestResult testCPUFloat() { auto start = std::chrono::high_resolution_clock::now(); const int size = 500000; // 减少数据量以加快测试 std::vector<double> data(size); // 初始化数据 for (int i = 0; i < size; i++) { data[i] = i + 1.0; } // 执行浮点运算 for (int i = 0; i < 50; ++i) { // 减少迭代次数 for (int j = 0; j < size; ++j) { data[j] = std::sin(data[j]) * std::cos(data[j]) + std::sqrt(fabs(data[j])); } } auto end = std::chrono::high_resolution_clock::now(); double duration = std::chrono::duration<double>(end - start).count(); // 计算每秒浮点运算次数 double flops = (size * 50.0 * 5) / duration; // 5 operations per iteration TestResult result; result.name = "CPU浮点性能"; result.rawValue = flops / 1e9; // 转换为GFlops result.unit = "GFlops"; // 评分标准:0.5 GFlops = 10分, 50 GFlops = 100分 result.score = normalizeScore(result.rawValue, 0.5, 50.0); result.weight = 0.30; return result; } // CPU性能测试 - 整数运算 TestResult testCPUInteger() { auto start = std::chrono::high_resolution_clock::now(); const int size = 5000000; // 减少数据量 std::vector<int> data(size); // 初始化数据 for (int i = 0; i < size; i++) { data[i] = i + 1; } // 执行整数运算 for (int i = 0; i < 25; ++i) { // 减少迭代次数 for (int j = 0; j < size; ++j) { data[j] = (data[j] * 3 + 7) % 1000; data[j] = data[j] ^ (data[j] << 13); data[j] = data[j] ^ (data[j] >> 17); data[j] = data[j] ^ (data[j] << 5); } } auto end = std::chrono::high_resolution_clock::now(); double duration = std::chrono::duration<double>(end - start).count(); // 计算每秒整数运算次数 double iops = (size * 25.0 * 4) / duration; TestResult result; result.name = "CPU整数性能"; result.rawValue = iops / 1e9; // 转换为GIOps result.unit = "GIOps"; // 评分标准:0.5 GIOps = 10分, 25 GIOps = 100分 result.score = normalizeScore(result.rawValue, 0.5, 25.0); result.weight = 0.30; return result; } // 内存性能测试 TestResult testMemory() { const size_t size = 50 * 1024 * 1024; // 50MB std::vector<char> buffer(size); // 写入测试 auto startWrite = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < size; i += 128) { // 增加步长 buffer[i] = static_cast<char>(i % 256); } auto endWrite = std::chrono::high_resolution_clock::now(); // 读取测试 char dummy = 0; // 防止编译器优化 auto startRead = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < size; i += 128) { dummy += buffer[i]; } auto endRead = std::chrono::high_resolution_clock::now(); // 使用dummy防止优化 if (dummy == 0) {} double writeTime = std::chrono::duration<double>(endWrite - startWrite).count(); double readTime = std::chrono::duration<double>(endRead - startRead).count(); double writeSpeed = (size / writeTime) / (1024.0 * 1024 * 1024); // GB/s double readSpeed = (size / readTime) / (1024.0 * 1024 * 1024); // GB/s double avgSpeed = (writeSpeed + readSpeed) / 2.0; TestResult result; result.name = "内存性能"; result.rawValue = avgSpeed; result.unit = "GB/s"; // 评分标准:1 GB/s = 20分, 20 GB/s = 100分 result.score = normalizeScore(avgSpeed, 1.0, 20.0); result.weight = 0.20; return result; } // 文件I/O性能测试 TestResult testFileIO() { const char* testFile = "benchmark_test.bin"; const size_t fileSize = 25 * 1024 * 1024; // 25MB std::vector<char> buffer(512 * 1024); // 512KB buffer // 填充随机数据 for (size_t i = 0; i < buffer.size(); i++) { buffer[i] = static_cast<char>(i % 256); } // 写入测试 auto startWrite = std::chrono::high_resolution_clock::now(); std::ofstream outFile(testFile, std::ios::binary); if (outFile) { for (size_t i = 0; i < fileSize; i += buffer.size()) { outFile.write(buffer.data(), buffer.size()); } outFile.close(); } auto endWrite = std::chrono::high_resolution_clock::now(); // 读取测试 auto startRead = std::chrono::high_resolution_clock::now(); std::ifstream inFile(testFile, std::ios::binary); if (inFile) { while (inFile.read(buffer.data(), buffer.size())) { // Just reading } inFile.close(); } auto endRead = std::chrono::high_resolution_clock::now(); // 清理测试文件 remove(testFile); double writeTime = std::chrono::duration<double>(endWrite - startWrite).count(); double readTime = std::chrono::duration<double>(endRead - startRead).count(); double writeSpeed = 0, readSpeed = 0; if (writeTime > 0) writeSpeed = (fileSize / writeTime) / (1024.0 * 1024); // MB/s if (readTime > 0) readSpeed = (fileSize / readTime) / (1024.0 * 1024); // MB/s double avgSpeed = (writeSpeed + readSpeed) / 2.0; TestResult result; result.name = "磁盘I/O性能"; result.rawValue = avgSpeed; result.unit = "MB/s"; // 评分标准:30 MB/s = 10分, 500 MB/s = 100分 result.score = normalizeScore(avgSpeed, 30.0, 500.0); result.weight = 0.20; return result; } // 运行所有测试 void runAllTests() { std::cout << "开始性能测试..." << std::endl; std::cout << "==================================" << std::endl; // 显示系统信息 std::cout << "系统信息:" << std::endl; std::cout << " CPU核心数: " << SystemInfo::getCPUThreads() << std::endl; std::cout << " 内存大小: " << std::fixed << std::setprecision(1) << SystemInfo::getMemoryGB() << " GB" << std::endl; std::cout << "==================================" << std::endl; // 运行各个测试 std::cout << "测试 1/4 进行中..." << std::endl; try { results.push_back(testCPUFloat()); std::cout << " CPU浮点性能 完成" << std::endl; } catch (const std::exception& e) { std::cout << " CPU浮点性能测试失败: " << e.what() << std::endl; } std::cout << "测试 2/4 进行中..." << std::endl; try { results.push_back(testCPUInteger()); std::cout << " CPU整数性能 完成" << std::endl; } catch (const std::exception& e) { std::cout << " CPU整数性能测试失败: " << e.what() << std::endl; } std::cout << "测试 3/4 进行中..." << std::endl; try { results.push_back(testMemory()); std::cout << " 内存性能 完成" << std::endl; } catch (const std::exception& e) { std::cout << " 内存性能测试失败: " << e.what() << std::endl; } std::cout << "测试 4/4 进行中..." << std::endl; try { results.push_back(testFileIO()); std::cout << " 磁盘I/O性能 完成" << std::endl; } catch (const std::exception& e) { std::cout << " 磁盘I/O性能测试失败: " << e.what() << std::endl; } std::cout << "==================================" << std::endl; std::cout << "所有测试完成!" << std::endl; } // 显示测试结果 void displayResults() { std::cout << "\n性能测试结果:" << std::endl; std::cout << "==================================" << std::endl; std::cout << std::left << std::setw(20) << "测试项目" << std::setw(12) << "分数" << std::setw(12) << "权重" << std::setw(15) << "原始值" << std::setw(10) << "单位" << std::endl; std::cout << "----------------------------------" << std::endl; double totalScore = 0.0; double totalWeight = 0.0; for (const auto& result : results) { std::cout << std::left << std::setw(20) << result.name << std::setw(12) << std::fixed << std::setprecision(1) << result.score << std::setw(12) << std::fixed << std::setprecision(2) << result.weight << std::setw(15) << std::fixed << std::setprecision(2) << result.rawValue << std::setw(10) << result.unit << std::endl; totalScore += result.score * result.weight; totalWeight += result.weight; } std::cout << "==================================" << std::endl; // 计算综合得分 double finalScore = (totalWeight > 0) ? totalScore / totalWeight : 0; std::cout << "\n综合性能得分: " << std::fixed << std::setprecision(1) << finalScore << "/100" << std::endl; // 性能评级 std::cout << "性能评级: "; if (finalScore >= 90) { std::cout << "极佳"; } else if (finalScore >= 80) { std::cout << "优秀"; } else if (finalScore >= 70) { std::cout << "良好"; } else if (finalScore >= 60) { std::cout << "中等"; } else if (finalScore >= 50) { std::cout << "一般"; } else { std::cout << "较差"; } std::cout << std::endl; } }; int main() { std::cout << "电脑性能测试工具" << std::endl; std::cout << "=====================" << std::endl; std::cout << "注意:测试过程中电脑可能会出现卡顿,这是正常现象。" << std::endl; std::cout << "测试可能需要几分钟时间,请耐心等待..." << std::endl; std::cout << std::endl; Benchmark benchmark; char choice; std::cout << "是否开始性能测试?(y/n): "; std::cin >> choice; if (choice == 'y' || choice == 'Y') { benchmark.runAllTests(); benchmark.displayResults(); } else { std::cout << "测试已取消。" << std::endl; } std::cout << "\n按任意键退出..." << std::endl; std::cin.ignore(); std::cin.get(); return 0; }

测试项目:

  1. CPU浮点性能:测试科学计算能力

  2. CPU整数性能:测试通用计算能力

  3. 内存性能:测试内存读写速度

  4. 磁盘I/O性能:测试硬盘读写速度

权重分配:

  • CPU浮点性能:30%

  • CPU整数性能:30%

  • 内存性能:20%

  • 磁盘I/O性能:20%

这个版本应该能在大多数C++编译器上编译运行,包括较老的编译器版本。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/30 20:09:36

NoneBot2驱动器性能对比:5种驱动引擎深度测评与选择策略

NoneBot2驱动器性能对比&#xff1a;5种驱动引擎深度测评与选择策略 【免费下载链接】nonebot2 跨平台 Python 异步聊天机器人框架 / Asynchronous multi-platform chatbot framework written in Python 项目地址: https://gitcode.com/gh_mirrors/no/nonebot2 你是否在…

作者头像 李华
网站建设 2026/5/29 19:38:31

高效FLARE-VM配置指南:搭建专业级逆向工程环境

在逆向工程和恶意软件分析领域&#xff0c;一个功能完整、配置得当的分析环境是提高工作效率的关键。FLARE-VM作为专为安全研究人员设计的虚拟机环境配置工具&#xff0c;通过自动化安装和智能配置&#xff0c;让你快速拥有一个专业级的分析工作站。本指南将带你深入了解FLARE-…

作者头像 李华
网站建设 2026/5/29 19:51:52

从菜鸟到专家,网络安全工程师必备证书,如何报考?

网络空间的竞争&#xff0c;归根结底是人才的竞争。 在2022年网络安全周上&#xff0c;《网络安全人才实战能力白皮书》正式发布。数据显示&#xff0c;到2027年&#xff0c;我国网络安全人员缺口将达327万&#xff0c;而高校人才培养规模仅为3万/年。 那么&#xff0c;如果你…

作者头像 李华
网站建设 2026/5/29 7:15:28

最佳电脑录屏工具Bandicam,支持4K画质,游戏录屏录课必备工具

Bandicam&#xff08;班迪录屏&#xff09;是一款专业的录屏软件&#xff0c;能录制电脑屏幕上的所有操作过程&#xff0c;适用于网络教学、课件制作、在线视频、直播视频等。它具备丰富的视频特效&#xff0c;可添加水印图片、鼠标点击效果&#xff0c;以及在录制中实时添加线…

作者头像 李华
网站建设 2026/5/29 19:44:34

Flutter国际化终极指南:Easy Localization完整教程

Flutter国际化终极指南&#xff1a;Easy Localization完整教程 【免费下载链接】easy_localization Easy and Fast internationalizing your Flutter Apps 项目地址: https://gitcode.com/gh_mirrors/ea/easy_localization 想象一下&#xff0c;你的Flutter应用能在全球…

作者头像 李华