# C++ 简单的程序段记时工具

基于宏定义的几个C++记时工具,实现类似于MATLAB中tic().toc()的功能

代码

#include <ctime>

#define def_tic(name) clock_t t_##name
#define rec_tic(name) t_##name = clock()
#define cost_time(name) double(clock()-(t_##name))/CLOCKS_PER_SEC

#define tic(name) def_tic(name); rec_tic(name)
#define toc(name) std::cout<<"[ "<<#name<<" ]"<<" cost "<<cost_time(name)<<" s"<<std::endl

测试

#include<bits/stdc++.h>

#define def_tic(name) clock_t t_##name
#define rec_tic(name) t_##name = clock()
#define cost_time(name) double(clock()-(t_##name))/CLOCKS_PER_SEC

#define tic(name) def_tic(name); rec_tic(name)
#define toc(name) std::cout<<"[ "<<#name<<" ]"<<" cost "<<cost_time(name)<<" s"<<std::endl

using namespace std;

int main(){
    int N=1e8;
    vector<int> vec;
    tic(Using_Push_Back);
    for(int i=0;i<N;i++)
        vec.push_back(i);
    toc(Using_Push_Back);

    vector<int> vec2;
    vec2.reserve(N);
    tic(Using_Emplace_Back);
    for(int i=0;i<N;i++)
        vec2.emplace_back(i);
    toc(Using_Emplace_Back);
    return 0;
}

输出

[ Using_Push_Back ] cost 0.224 s
[ Using_Emplace_Back ] cost 0.121 s

使用预先reserve分配内存,emplace_back()可以提高vector容器使用效率。

posted @ 2022-09-01 11:13  陈橙橙  阅读(51)  评论(0编辑  收藏  举报