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.

  1. untill c11 time() returns seconds since 01/01/1970 00:00 utc integral value. results make me assume, using c11 or above, since time_t floating point value. (see) anyway, standard not give guarantees precission , runtime of time(). you'd have subtract that.

  2. 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

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -