linux - Is my C++ code to measure context switch time correct? -
i wrote c++ code below measure time context switching on linux. got result 3.98757e-06 second, seems longer expected.
can tell me if code correct? ( computer has 4 processors 1199, 2534, 3072, 1199 mhz respectively , not sure if information related ).
#include <iostream> #include <mutex> #include <thread> #include <condition_variable> #include <time.h> using namespace std; bool flag = false; int counter = 0; mutex mtx; condition_variable setcv, unsetcv; time_t timer1 = time(null); time_t timer2 = timer1; void setflag(){ unique_lock<mutex> lk( mtx ); while( flag ){ setcv.wait( lk ); } flag = true; counter++; unsetcv.notify_one(); } void unsetflag(){ unique_lock<mutex> lk( mtx ); while( !flag ){ unsetcv.wait( lk ); } flag = false; counter++; setcv.notify_one(); } void setagent(){ while( difftime( timer2, timer1 ) < 1 ){ setflag(); timer2 = time( null ); } } void unsetagent(){ while( difftime( timer2, timer1 ) < 1 ){ unsetflag(); timer2 = time( null ); } } int main(){ thread ithread = thread( setagent ); thread dthread = thread( unsetagent ); ithread.join(); dthread.join(); cout << (float) 1 / counter << endl; } i noticed post how measure time of switching process context in linux using c++?, no code there.
untill c11
time()returns seconds since 01/01/1970 00:00 utc integral value. results make me assume, using c11 or above, sincetime_tfloating point value. (see) anyway, standard not give guarantees precission , runtime oftime(). you'd have subtract that.your assumptions on way scheduler decide run second thread not reliable. best thing can use cpu-shielding, wouldn't count on results then. make lot of measurements, drop 10% highest , lowest results, take average. might give close enough , rather stable figure.
Comments
Post a Comment