第三章 UT单元测试——CPU与内存使用率限制

系列文章目录

第一章 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与内存的限制,而在实际测试中需要根据实际情况添加更多限制和约束,例如磁盘、网络使用率等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喜乐boy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值