0

Given using C++ or C, how could I measure how long it takes to do a thread switch under linux?Is it possible? At most platform, how long does it takes?Could anybody give me some typical value?

I don't wanna to measure thread quantum indeed. I hope to find a practical method to measure the duration of swithing a thread to another(not how long a thread could run).

I would appreciate that if you could provide the code.

I would be grateful for any hint on this question.

sunshilong369
  • 646
  • 1
  • 5
  • 17

1 Answers1

1

See you again :)

It is possible, but you need to do a little change about kernel code. So openwrt or something else may be good for you.

You can see my blog and the source code to solve the problem. The preemption schedule will do the time check, and it is like below

/*
 * Preempt the current task with a newly woken task if needed:
 */
static void
check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
{
    unsigned long ideal_runtime, delta_exec;
    struct sched_entity *se;
    s64 delta;
    ideal_runtime = sched_slice(cfs_rq, curr);
    delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
    if (delta_exec > ideal_runtime) {
        resched_curr(rq_of(cfs_rq));
        /*
         * The current task ran long enough, ensure it doesn't get
         * re-elected due to buddy favours.
         */
        clear_buddies(cfs_rq, curr);
        return;
    }
    /*
     * Ensure that a task that missed wakeup preemption by a
     * narrow margin doesn't have to wait for a full slice.
     * This also mitigates buddy induced latencies under load.
     */
    if (delta_exec < sysctl_sched_min_granularity)
        return;
    se = __pick_first_entity(cfs_rq);
    delta = curr->vruntime - se->vruntime;
    if (delta < 0)
        return;
    if (delta > ideal_runtime)
        resched_curr(rq_of(cfs_rq));
}

Here we have several time helpful for you

ideal_runtime : the time this task run in this schedule period

sum_exec_runtime : total time the task run

prev_sum_exec_runtime : history total time

tyChen
  • 1,404
  • 8
  • 27
  • Chen, glad to see you, too.Thank you for the clarification. – sunshilong369 Jun 02 '20 at 04:56
  • You're welcome. If you have any other problems maybe we can talk about them. – tyChen Jun 02 '20 at 04:58
  • If i understand you correctly, it could not be done under user space without modifying any kernel source code, because you could not know when the current thread begins to be switched out at all.Am i right? – sunshilong369 Jun 02 '20 at 05:06
  • You're right, you need to add some little function in kernel, or maybe there are some functions can do it in user space but I don't know. I think ptrace may work but I haven't try it so I'm not sure. – tyChen Jun 02 '20 at 06:44