C++程序计时

一般方法可以使用ctime库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <ctime>

using namespace std;

int main(int argc, const char * argv[]) {

clock_t begin = clock();

//code

clock_t end = clock();
double t = static_cast<double>(end - begin) / CLOCKS_PER_SEC;
cout << t << endl;
return 0;
}

在sf上看到一个比较C++风格的方法.借助 std::chrono::duration 与 lambda 函数.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <chrono>

template<typename TimeT = std::chrono::milliseconds>
struct measure
{
template<typename F, typename ...Args>
static typename TimeT::rep execution(F func, Args&&... args)
{
auto start = std::chrono::system_clock::now();

// Now call the function with all the parameters you need.
func(std::forward<Args>(args)...);

auto duration = std::chrono::duration_cast< TimeT>
(std::chrono::system_clock::now() - start);

return duration.count();
}
};

struct functor
{
int state;
functor(int state) : state(state) {}
void operator()() const
{
std::cout << "In functor run for ";
}
};

void func()
{
std::cout << "In function, run for " << std::endl;
}

int main()
{
// codes directly
std::cout << measure<>::execution([&]() {
// your code
}) << " ms" << std::endl;

// functor
std::cout << measure<>::execution(functor(3)) << std::endl;

// function
std::cout << measure<>::execution(func);
}

改变精度,仅需修改 template 中的参数即可:

milliseconds : 毫秒

microseconds : 微秒

nanoseconds : 纳秒

原地址: https://segmentfault.com/a/1190000002548499

script>