Measuring execution time of a function in C++

后端 未结 11 821
小鲜肉
小鲜肉 2020-11-22 12:59

I want to find out how much time a certain function takes in my C++ program to execute on Linux. Afterwards, I want to make a speed comparison . I saw sever

11条回答
  •  天涯浪人
    2020-11-22 13:15

    Here's a function that will measure the execution time of any function passed as argument:

    #include 
    #include 
    
    typedef std::chrono::high_resolution_clock::time_point TimeVar;
    
    #define duration(a) std::chrono::duration_cast(a).count()
    #define timeNow() std::chrono::high_resolution_clock::now()
    
    template
    double funcTime(F func, Args&&... args){
        TimeVar t1=timeNow();
        func(std::forward(args)...);
        return duration(timeNow()-t1);
    }
    

    Example usage:

    #include 
    #include 
    
    typedef std::string String;
    
    //first test function doing something
    int countCharInString(String s, char delim){
        int count=0;
        String::size_type pos = s.find_first_of(delim);
        while ((pos = s.find_first_of(delim, pos)) != String::npos){
            count++;pos++;
        }
        return count;
    }
    
    //second test function doing the same thing in different way
    int countWithAlgorithm(String s, char delim){
        return std::count(s.begin(),s.end(),delim);
    }
    
    
    int main(){
        std::cout<<"norm: "<

    Output:

    norm: 15555
    algo: 2976
    

提交回复
热议问题