增加cpu loading 背景:在版本发布后需要在指定负载情况下测试程序性能 代码很简单,就是启动N个线程,每个线程做 S 次循环自增,然后再休眠 U 秒,如此往复。可以达到以模拟以下场
增加cpu loading
背景:在版本发布后需要在指定负载情况下测试程序性能
代码很简单,就是启动N个线程,每个线程做S
次循环自增,然后再休眠U
秒,如此往复。可以达到以模拟以下场景:
-
- 在空负载的情况下将单核或者多核的cpu loading增加到指定阈值
-
- 增加较多的线程数达到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)