【问题标题】:Counting context switches per thread计算每个线程的上下文切换
【发布时间】:2011-01-27 11:16:42
【问题描述】:

有没有办法查看每个线程生成了多少上下文切换? (如果可能,进出)要么在 X/s 中,要么让它运行并在一段时间后提供聚合数据。 (在 linux 或 windows 上)

我发现只有工具可以为整个操作系统或每个进程提供聚合的上下文切换数。

我的程序进行了许多上下文切换 (50k/s),可能很多都没有必要,但我不确定从哪里开始优化,其中大部分发生在哪里。

【问题讨论】:

标签: performance optimization operating-system context-switch


【解决方案1】:

我有一个 bash 脚本,用于计算线程在特定时间范围内进行的自愿和非自愿上下文切换。我不确定这是否会达到您的目的,但无论如何我都会发布它。

此脚本循环处理进程的所有线程并记录来自/proc/< process-id>/task/< thread-id>/status"voluntary_ctxt_switches" & "nonvoluntary_ctxt_switches"。我通常做的是在性能运行开始时记录这些计数器并在运行结束时再次记录,然后在性能运行期间计算总vol & non-vol ctx 开关的差异。

pid=`ps -ef | grep <process name> | grep $USER | grep -v grep | awk '{print $2}'`
echo "ThreadId;Vol_Ctx_Switch;Invol_Ctx_Switch"
for tid in `ps -L --pid ${pid}  | awk '{print $2}'`
do
    if [ -f /proc/$pid/task/$tid/status ]
    then
        vol=`cat /proc/$pid/task/$tid/status | grep voluntary_ctxt_switches | grep -v nonvoluntary_ctxt_switches | awk '{print $NF}'`
        non_vol=`cat /proc/$pid/task/$tid/status | grep nonvoluntary_ctxt_switches | awk '{print $NF}'`
    fi
    echo "$tid;$vol;$non_vol"
done

脚本有点重,在我的例子中,进程有大约 2500 个线程。收集 ctx 开关的总时间约为 10 秒。

【讨论】:

    【解决方案2】:

    Linux

    我写了一个小脚本来查看进程的特定线程的细节。通过执行此脚本,您还可以看到上下文切换。

    if [ "$#" -ne 2 ]; then
        echo "INVALID ARGUMENT ERROR: Please use ./see_thread.sh processName threadNumber"
        exit
    fi
    ls /proc/`pgrep $1`/task | head -n$2 | tail -n+$2>temp
    cat /proc/`pgrep $1`/task/`cat temp`/sched
    

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      在最近的 GNU/Linux 系统上,您可以使用 SystemTap 在每次调用 sched_switch() 时收集您想要的数据。 schedtimes.stp 示例可能是一个好的开始:http://sourceware.org/systemtap/examples/keyword-index.html#SCHEDULER

      【讨论】:

        猜你喜欢
        • 2011-07-23
        • 1970-01-01
        • 2017-09-09
        • 2011-07-27
        • 2010-09-23
        • 2012-09-18
        • 2012-01-12
        • 1970-01-01
        相关资源
        最近更新 更多