简体   繁体   English

C ++如何测量和比较两个函数之间的执行时间

[英]C++ How to measure and compare execution time between two functions

I'm new to C++我是 C++ 新手

And I'm trying to build a simple project, so I need to measure and compare execution time between two functions, to see which one is better for performance time,而且我正在尝试构建一个简单的项目,所以我需要测量和比较两个函数之间的执行时间,看看哪个函数的性能时间更好,

I know there are a lot of ways like calculating start and end time and calc difference But that's not usually true, so there's no right way to do it?我知道有很多方法,比如计算开始时间和结束时间以及计算差异,但这通常不是真的,所以没有正确的方法吗?

my old code:我的旧代码:

#include <chrono>

auto begin = std::chrono::steady_clock::now();
/* some code*/
auto end = std::chrono::steady_clock::now();

auto time = (end - begin).count();

Any help please?请问有什么帮助吗?

using C++ Timeit library :使用C++ Timeit 库

Compare Time Between Two Functions比较两个函数之间的时间

void func1() { /* some code */ }
void func2() { /* some code */ }

compareit(1000,func1,func2);

result结果

[COMPARE IT] first(675)  > second(22) x30

NOTES笔记

first means first function func1() first表示第一个函数 func1()

second means second function func2() second表示第二个函数 func2()

x30 means the func2() faster than func1() by 30 times x30表示 func2() 比 func1() 快 30 倍

675 22 it is a elapsed time to execute func1 , func2 for 1000 times 675 22 func1func2执行1000次的经过时间


Measure Time For One Function测量一项功能的时间

void func() { for (auto i = 0; i < 10; i++) sqrt(i); }
std::cout << timeit(1000, func).nanoseconds() << std::endl;

result结果

225451

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM