mardi 1 octobre 2019

Std::chrono gives different value while used from main or from class method

I have created utility class in c++ to be able to get the run time of different methods. I am trying to store time calculated using chrono in a struct so I can store all the methods I am using in the program to be measured and printed at the end. The problem is most of the time when I call that from a method it returns 0 as output, but if I use chrono in the main function it gives actual output.

Below is how I have created the methods in c++ file to collect time from different functions (Header and cpp is different but I have declared struct in the cpp file directly):

Struct Declaration and initialization:

struct analysis{
    const char * func_name;
    int calc_time;
    analysis(const char* x, const int y):
    func_name(x), calc_time(y){}
};
vector<analysis> time_coll {};

method to start storing the time:

void Utility::tStart(){
      auto chrono_strt = chrono::high_resolution_clock::now(); 
      sink = chrono_strt;
}

method to stop storing the time:

void Utility::tEnd(const char* func_name){
    std::chrono::high_resolution_clock::time_point chrono_stp = chrono::high_resolution_clock::now(); 
    std::chrono::microseconds elapsed = std::chrono::duration_cast<std::chrono::microseconds>(chrono_stp - sink);    
    time_coll.push_back((analysis(func_name, elapsed.count())));    
}

method to print the time at end:

void Utility::pStat(){
    for( const auto& elem: time_coll){
        cout << elem.func_name  << " : " << elem.calc_time << endl;
    }
}

Sample of usage in other method:

void Sort::BubbleSort(vector<int>& a){
    u.tStart();
    int temp;
    for (int i=0; i<=(a.size());i++){
        for(int j=0; j<=(a.size())-2;j++){
            if(a[j]>a[j+1]){
                temp = a[j];
                a[j] = a[j+1];
                a[j+1] = temp;
            }
        }

    }
    u.tEnd(__FUNCTION__);
}

The above methods mostly produces 0 as outcome except that I give extremely large input to function(I have tested it on bubble sort). When I call the chrono in main file from start to end (without using the above mentioned methods), I am getting current outcome.

Aucun commentaire:

Enregistrer un commentaire