我在下面编写了C ++代码来测量Linux上下文切换的时间。我得到了结果3.98757e-06秒,这看起来比我预期的要长得多。
有人能告诉我我的代码是否正确吗? (我的电脑有4个处理器,分别是1199,2534,3072,1199 MHz,我不确定这些信息是否相关)。
#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;
}
我注意到帖子How to measure a time of switching process context in Linux using C++?,但没有代码。
答案 0 :(得分:0)
直到C11 time()
返回自01/01/1970 00:00 UTC以来的秒数作为整数值。您的结果让我假设您使用的是C11或更高版本,因为time_t
是浮点值。 (see)无论如何,标准并未对time()
的精确度和运行时间提供任何保证。你必须减去它。
您对调度程序决定运行第二个线程的方式的假设是不可靠的。你能做的最好的事情就是使用CPU屏蔽,但即便如此,我也不会依赖于结果。进行大量测量,降低10%的最高和最低结果,取平均值。这可能会给出一个足够接近且相当稳定的数字。