#include <gtest/gtest.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <iostream>
#include <unistd.h>
// 一些系统相关函数,统计代码时间之类的功能
/**
* 统计代码运行时间
* @tparam FuncT
* @param func 被调用函数
* @param func_name 函数名
* @param times 调用次数
*/
template <typename FuncT>
void evaluate_and_call(FuncT&& func, const std::string& func_name = "", int times = 10) {
double total_time = 0;
for (int i = 0; i < times; ++i) {
auto t1 = std::chrono::high_resolution_clock::now();
func();
auto t2 = std::chrono::high_resolution_clock::now();
total_time += std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1).count() * 1000;
}
LOG(INFO) << "方法 " << func_name << " 平均调用时间/次数: " << total_time / times << "/" << times << " 毫秒.";
}
void testfunc()
{
std::cout << "start testfunc" << std::endl;
usleep(500000);
std::cout << "end testfunc" << std::endl;
}
TEST(myTest, test1)
{
evaluate_and_call(testfunc, "test my testfunc", 5);
}
int main(int argc, char* argv[])
{
printf("Running main() from %s\n", __FILE__);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
CmakeLists.txt
# 工程名
set (PROJECT_NAME my-gtest)
PROJECT(${PROJECT_NAME})
message("工程名: " ${PROJECT_NAME})
message("工程目录: " ${PROJECT_SOURCE_DIR})
cmake_minimum_required(VERSION 3.6)
set(CMAKE_CXX_STANDARD 17)
SET(CMAKE_BUILD_TYPE "DEBUG")
add_executable(${PROJECT_NAME} testGtest.cpp)
target_link_libraries(${PROJECT_NAME}
gtest pthread glog gflags tbb
)