【发布时间】:2016-07-04 17:58:39
【问题描述】:
我想计算上下文切换时间,我正在考虑使用互斥锁和条件变量在 2 个线程之间发出信号,以便一次只运行一个线程。我可以使用CLOCK_MONOTONIC 测量整个执行时间,使用CLOCK_THREAD_CPUTIME_ID 测量每个线程运行的时间。
那么上下文切换时间就是(total_time - thread_1_time - thread_2_time)。
为了得到更准确的结果,我可以遍历它并取平均值。
这是近似上下文切换时间的正确方法吗?我想不出任何可能出错的地方,但我得到的答案不到 1 纳秒..
我忘了提到,我循环的时间越多,取平均值,我得到的结果就越小。
编辑
这是我拥有的代码的 sn-p
typedef struct
{
struct timespec start;
struct timespec end;
}thread_time;
...
// each thread function looks similar like this
void* thread_1_func(void* time)
{
thread_time* thread_time = (thread_time*) time;
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &(thread_time->start));
for(x = 0; x < loop; ++x)
{
//where it switches to another thread
}
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &(thread_time->end));
return NULL;
};
void* thread_2_func(void* time)
{
//similar as above
}
int main()
{
...
pthread_t thread_1;
pthread_t thread_2;
thread_time thread_1_time;
thread_time thread_2_time;
struct timespec start, end;
// stamps the start time
clock_gettime(CLOCK_MONOTONIC, &start);
// create two threads with the time structs as the arguments
pthread_create(&thread_1, NULL, &thread_1_func, (void*) &thread_1_time);
pthread_create(&thread_2, NULL, &thread_2_func, (void*) &thread_2_time);
// waits for the two threads to terminate
pthread_join(thread_1, NULL);
pthread_join(thread_2, NULL);
// stamps the end time
clock_gettime(CLOCK_MONOTONIC, &end);
// then I calculate the difference between between total execution time and the total execution time of two different threads..
}
【问题讨论】:
-
您是否确保它们运行在同一个处理器内核上,也许是
sched_set_affinity
标签: c multithreading time