- for循环条件中调用普通函数
#include <iostream>
#include <chrono>
using namespace std;
long long count = 0;
const int N = 10;
int getSize(){
cout<<"get size"<<endl;
return N + 1;
}
void timeMeasure(void(*f)()){
auto begin = std::chrono::high_resolution_clock::now();
uint32_t iterations = 1;
for(uint32_t i = 0; i < iterations; ++i)
{
f();
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count();
std::cout << duration << "ns total, average : " << duration / iterations << "ns." << std::endl;
}
void test1(){
for(int i = 0; i < getSize(); ++i){
count++;
}
}
void test2(){
for(int i = 0; i < N + 1; ++i){
count++;
}
}
int main(){
timeMeasure(test1);
cout<<count<<endl;
timeMeasure(test2);
cout<<count<<endl;
return 0;
}
8642ns total, average : 86ns.
1000
6502ns total, average : 65ns.
2000
- 探究vector size()函数
#include <iostream>
#include <chrono>
#include <vector>
using namespace std;
long long count = 0;
const int N = 100;
vector<int> arr1;
vector<int> arr2;
void timeMeasure(void(*f)()){
auto begin = std::chrono::high_resolution_clock::now();
uint32_t iterations = 2;
for(uint32_t i = 0; i < iterations; ++i)
{
f();
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count();
std::cout << duration << "ns total, average : " << duration / iterations << "ns." << std::endl;
}
void test1(){
for(int i = 0; i < arr1.size(); ++i){
count++;
}
}
void test2(){
int num = arr2.size();
for(int i = 0; i < num; ++i){
count++;
}
}
int main(){
arr1.assign(N, 0);
arr2.assign(N, 0);
timeMeasure(test1);
cout<<count<<endl;
timeMeasure(test2);
cout<<count<<endl;
return 0;
}
3412ns total, average : 1706ns.
200
1675ns total, average : 837ns.
400
标签:std,count,include,average,long,C++,调用函数,total,优化
From: https://www.cnblogs.com/qiangz/p/17303673.html