news 2026/9/21 14:39:43

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/9/21 6:32:35

Monkey‘s Audio(无损音频压缩器)

链接&#xff1a;https://pan.quark.cn/s/4cef50ed0d24Monkey’s Audio是一套快速且易于操作的数字音乐压缩方案&#xff0c;可将WAV转成APE的音乐文件&#xff0c;他不像一般的MP3或OGG音乐格式&#xff0c;为了节省空间而失去了应有的音乐品质。强调的是保有原来的高品质音质…

作者头像 李华
网站建设 2026/9/21 23:01:59

ChatPDF终极指南:5分钟学会与PDF文档智能对话

还在为翻阅冗长PDF文档而烦恼吗&#xff1f;ChatPDF让文档阅读变得像聊天一样简单&#xff01;这个基于本地LLM的开源项目&#xff0c;通过先进的检索增强生成技术&#xff0c;让您能够与任何PDF、DOCX、TXT文件进行自然语言对话。 【免费下载链接】ChatPDF RAG for Local LLM,…

作者头像 李华
网站建设 2026/9/20 22:36:27

如何快速解决ComfyUI-SeedVR2依赖冲突:完整避坑指南

如何快速解决ComfyUI-SeedVR2依赖冲突&#xff1a;完整避坑指南 【免费下载链接】ComfyUI-SeedVR2_VideoUpscaler Non-Official SeedVR2 Vudeo Upscaler for ComfyUI 项目地址: https://gitcode.com/gh_mirrors/co/ComfyUI-SeedVR2_VideoUpscaler ComfyUI-SeedVR2视频超…

作者头像 李华
网站建设 2026/9/20 16:14:09

Java并发编程利器:从ConcurrentHashMap到Fork/Join的奇幻之旅

言&#xff1a;为什么我们需要并发容器&#xff1f;想象一下传统的超市结账场景&#xff1a;只有一个收银台&#xff0c;所有人排成一队&#xff0c;效率低下。这就是传统集合在多线程环境下的写照。而现代并发容器就像拥有多个收银台的智能超市&#xff1a;多个收银台同时工作…

作者头像 李华
网站建设 2026/9/20 18:40:05

5分钟掌握IOPaint集成:从零部署到深度定制全攻略

5分钟掌握IOPaint集成&#xff1a;从零部署到深度定制全攻略 【免费下载链接】IOPaint 项目地址: https://gitcode.com/GitHub_Trending/io/IOPaint 你是否在为网站添加专业图像编辑功能而烦恼&#xff1f;面对复杂的AI模型和繁琐的开发流程&#xff0c;很多开发者望而…

作者头像 李华
网站建设 2026/9/21 13:37:51

汽车变速器电控系统Simulink模型:从原理到实现

汽车变速器电控系统 Simulink 模型 汽车动力换挡变速器电控系统 变速器电控系统仿真 汽车/车辆电子课设设计该模型根据汽车动力换挡变速器的工作原理&#xff0c;设计出液压执行机构&#xff0c;确定控制器&#xff0c;制定汽车动力换挡变速器电控系统总体方案以及电控系统开发…

作者头像 李华