Brief introduction
Prior to the use of multi-threading to achieve accelerated, speaking about my first thread execution method commonly used to measure time. The basic idea is to achieve a measure of function, including representatives executed up.
The basic syntax
#include<iostream>
#include<thread>
using namespace std;
using namespace std::chrono; //增加引用空间
template<class T>
void measure(T&& func) {
auto beg_t = system_clock::now(); //开始时间
func(); //执行函数
auto end_t = system_clock::now(); //结束时间
duration<double> diff = end_t - beg_t;
printf("performTest total time: ");
cout << diff.count()<<endl;
}
void func() {
cout << "This is func thread " << endl;
int s = 0;
for (int i = 0; i < 5; i++)
s += i;
}
int main() {
measure(func);
}
Results of the
This is func thread
performTest total time: 0.0004911
Advanced version of the case: the use of lambda function to write compact executable some (see the election)
int main() {
int limit = 50;
measure([limit]() { //方括号捕捉外部变量limit
cout << "This is func thread " << endl;
int s = 0;
for (int i = 0; i < limit; i++)
s += i;
}
);
}
void measure(T&& func){
auto beg_t = system_clock::now();
func();
auto end_t = system_clock::now();
duration<double> diff = end_t - beg_t;
printf("PerformTest total time: ");
cout << diff.count()<<endl;
}
to sum up
This chapter describes how to use the function to measure execution time measure, the next section describes the specific process be accelerated.
Reference material
Links: cpp little knowledge --lambda expression .
Links: Tips common measurement function of time .