如何通过[C杂谈]增加CPU loading,提升系统运行效率?

2026-04-12 00:411阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计368个文字,预计阅读时间需要2分钟。

如何通过[C  杂谈]增加CPU loading,提升系统运行效率?

增加CPU+loading背景:在版本发布后,需在指定负载情况下测试程序性能。代码简单,即启动N个线程,每个线程执行S次循环自增,然后休眠U秒,如此循环。可模拟以下场景。

增加cpu loading

背景:在版本发布后需要在指定负载情况下测试程序性能

代码很简单,就是启动N个线程,每个线程做S次循环自增,然后再休眠U秒,如此往复。可以达到以模拟以下场景:

    1. 在空负载的情况下将单核或者多核的cpu loading增加到指定阈值
    1. 增加较多的线程数达到cpu上下文频繁切换的目的

代码

#include <chrono> #include <iostream> #include <array> #include <thread> #include <vector> void loading_func(int32_t sleep_us,int32_t step) { for(int32_t index = 0;index <= step;++index) { } std::this_thread::sleep_for(std::chrono::milliseconds(sleep_us)); } int main(int argc,char **argv) { auto thread_func = [](int32_t sleep_us,int32_t step){ while (true) { loading_func(sleep_us,step); } }; if (argc != 4) { printf("usage:%s thread_count sleep_us inc_step\r\n",argv[0]); exit(1); } int32_t thread_count = std::atoi(argv[1]); int32_t sleep_us = std::atoi(argv[2]); int32_t inc_step = std::atoi(argv[3]); std::vector<std::thread> threads; for (int32_t i = 0; i < thread_count;++i) { threads.emplace_back(std::thread(thread_func,sleep_us,inc_step)); } for (auto &t : threads) { t.join(); } return 0; }

cmakelists

project(cpuloading) set(bin_name ${PROJECT_NAME}) #set(CMAKE_CXX_FLAGS "-pthread -rt") aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR} SRC_FILES) add_executable(${bin_name} ${SRC_FILES}) target_link_libraries(${bin_name} rt pthread)

如何通过[C  杂谈]增加CPU loading,提升系统运行效率?

本文共计368个文字,预计阅读时间需要2分钟。

如何通过[C  杂谈]增加CPU loading,提升系统运行效率?

增加CPU+loading背景:在版本发布后,需在指定负载情况下测试程序性能。代码简单,即启动N个线程,每个线程执行S次循环自增,然后休眠U秒,如此循环。可模拟以下场景。

增加cpu loading

背景:在版本发布后需要在指定负载情况下测试程序性能

代码很简单,就是启动N个线程,每个线程做S次循环自增,然后再休眠U秒,如此往复。可以达到以模拟以下场景:

    1. 在空负载的情况下将单核或者多核的cpu loading增加到指定阈值
    1. 增加较多的线程数达到cpu上下文频繁切换的目的

代码

#include <chrono> #include <iostream> #include <array> #include <thread> #include <vector> void loading_func(int32_t sleep_us,int32_t step) { for(int32_t index = 0;index <= step;++index) { } std::this_thread::sleep_for(std::chrono::milliseconds(sleep_us)); } int main(int argc,char **argv) { auto thread_func = [](int32_t sleep_us,int32_t step){ while (true) { loading_func(sleep_us,step); } }; if (argc != 4) { printf("usage:%s thread_count sleep_us inc_step\r\n",argv[0]); exit(1); } int32_t thread_count = std::atoi(argv[1]); int32_t sleep_us = std::atoi(argv[2]); int32_t inc_step = std::atoi(argv[3]); std::vector<std::thread> threads; for (int32_t i = 0; i < thread_count;++i) { threads.emplace_back(std::thread(thread_func,sleep_us,inc_step)); } for (auto &t : threads) { t.join(); } return 0; }

cmakelists

project(cpuloading) set(bin_name ${PROJECT_NAME}) #set(CMAKE_CXX_FLAGS "-pthread -rt") aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR} SRC_FILES) add_executable(${bin_name} ${SRC_FILES}) target_link_libraries(${bin_name} rt pthread)

如何通过[C  杂谈]增加CPU loading,提升系统运行效率?