创建静态成员函数工具类
Utils.h
#define _CRT_SECURE_NO_WARNINGS
#pragma once
/**
* 通用工具类
*/
#include<string>
#include <chrono>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <thread>
using namespace std;
class Utils
{
public:
/**
* 获取当前时间字符串: yyyy-MM-dd HH:mm:ss
*/
static string getCurrentTimeStr();
/**
* 计算第n个斐波那契数
* @param n 输入参数
*/
static long fibo(int n);
static void info();
/**
* 统计函数运行时间
* 参数为函数传参示例: void f()
@param *pf 函数指针参数
*/
static void assessProcess(void (*pf)());
/**
* 统计函数运行时间
* 参数为函数传参示例: long f(int)
@param *pf 函数指针参数
@param n 传递函数的参数
*/
static void assessProcess(long (*pf)(int), int n);
};
Utils.cpp
#include "Utils.h"
string Utils::getCurrentTimeStr()
{
stringstream ss;
auto t = chrono::system_clock::to_time_t(std::chrono::system_clock::now());
ss << std::put_time(std::localtime(&t), "%Y-%m-%d %X");
return ss.str();
}
long Utils::fibo(int n)
{
long a = 0, b = 1;
int step = 1;
while (step++ <= n)
{
b = b + a;
a = b - a;
}
return a;
}
void Utils::info()
{
this_thread::sleep_for(std::chrono::seconds(2));
cout << "info function." << endl;
}
void Utils::assessProcess(void(*pf)())
{
auto beginTime = std::chrono::steady_clock::now();
(*pf)();
auto endTime = std::chrono::steady_clock::now();
double durationSecond = std::chrono::duration<double>(endTime - beginTime).count();
std::cout << "运行时间: " << durationSecond << "秒" << std::endl;
}
void Utils::assessProcess(long (*pf)(int), int n)
{
auto beginTime = std::chrono::steady_clock::now();
long res = (*pf)(n);
this_thread::sleep_for(std::chrono::seconds(1));
auto endTime = std::chrono::steady_clock::now();
cout << "函数执行结果: " << res << endl;
double durationSecond = std::chrono::duration<double>(endTime - beginTime).count();
std::cout << "运行时间: " << durationSecond << "秒" << std::endl;
}
创建主函数调用
Application.cpp
/**
* C++ 控制台
*/
#include <iostream>
#include <string>
#include <vector>
#include "Utils.h"
using namespace std;
int main()
{
Utils::assessProcess(Utils::info);
Utils::assessProcess(Utils::fibo, 13);
cout << "当前服务时间: " << Utils::getCurrentTimeStr() << endl;
return 0;
}