系列文章目录
第一章 UT单元测试——GoogleTest通用构建说明
第二章 UT单元测试——GTest框架实例
第三章 UT单元测试——CPU与内存使用率限制
前言
前两章介绍了GTest框架的构建和实例,笔者在测试过程中经常遇到CPU或是内存跑满的情况,现将解决办法整理于此。
一、环境配置
本文使用Linux环境。(后续补充)
二、使用步骤
1.添加待测源码
main.cpp(示例):
#include <iostream>
#define MAX_MEM_SIZE 1.5*1024*1024*1024
int main(int argc, char **argv) {
int i;
char* p;
fprintf(stdout, "assigning memory...");
p = (char *) malloc(MAX_MEM_SIZE);
fprintf(stdout, "assigned memory to p @ %lx\n", (int64_t) p);
for(i=0;i<MAX_MEM_SIZE;i++)
{
p[i] = i;
}
fprintf(stdout, "writen memory to p @ %lx, p[0]=%d\n", (int64_t) p, p[0]);
getchar();
free(p);
fprintf(stdout, "released memory from p @ %lx\n", (int64_t) p);
return 0;
}
2.编译待测源码
g++ -o main main.cpp
3.添加自动化脚本
run.sh:
# check for root
if [ x$(id -u) != x0 ]; then
echo Authorizing ...
printf -v cmd_str '%q ' "$0" "$@"
exec sudo su -c "$cmd_str"
else
echo Authorized
fi
echo Creating control group for memory:test ...
if [ ! -d "/sys/fs/cgroup/memory/test" ]; then
mkdir /sys/fs/cgroup/memory/test
fi
echo Writing memory limitation ...
echo 512M>/sys/fs/cgroup/memory/test/memory.limit_in_bytes
echo Checking memory limitation ...
echo Limit=$(cat /sys/fs/cgroup/memory/test/memory.limit_in_bytes)
echo Setting CPU limitation ...
# enable job control which is by default turned off in non-interactive mode
set -o monitor
cpulimit -e main -l 50 &
# disable job control
set +o monitor
echo $(jobs -l)
echo Launching program ...
echo ============================================
cgexec -g memory:test main
echo ============================================
echo Exiting program ...
echo $(jobs -l)
set -o monitor
fg 1
exit 0
4.测试
README.md:
A simple test case for cpu & memory limitation.
Linux command:
1. chmod +x run.sh
2. ./run.sh
5.运行结果
测试结果待补充。
总结
以上就是今天要讲的内容,本文仅仅简单介绍了CPU与内存的限制,而在实际测试中需要根据实际情况添加更多限制和约束,例如磁盘、网络使用率等。