C++函数运行时间统计示例:chrono/函数指针

创建静态成员函数工具类

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值