开发者

Counting context switches per thread

开发者 https://www.devze.com 2022-12-23 01:59 出处:网络
Is there a way to see how many context switches each thread generates? (both in and out if 开发者_运维技巧possible) Either in X/s, or to let it run and give aggregated data after some time.

Is there a way to see how many context switches each thread generates? (both in and out if 开发者_运维技巧possible) Either in X/s, or to let it run and give aggregated data after some time. (either on linux or on windows)

I have found only tools that give aggregated context-switching number for whole os or per process.

My program makes many context switches (50k/s), probably a lot not necessary, but I am not sure where to start optimizing, where do most of those happen.


On recent GNU/Linux systems you can use SystemTap to collect the data you want on every call to sched_switch(). The schedtimes.stp example is probably a good start: http://sourceware.org/systemtap/examples/keyword-index.html#SCHEDULER


Linux

I wrote a small script to see the details of a specific thread of the process. By executing this script you can see context switch as well.

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

Hope this will help.


I've a bash script that calculates voluntary and non-voluntary context switches made by a thread during a specific time frame. I'm not sure whether this will serve your purpose but I'll post it anyway.

This script is looping over all threads of a process and recording "voluntary_ctxt_switches" & "nonvoluntary_ctxt_switches" from /proc/< process-id>/task/< thread-id>/status. What I do generally is record these counters at the start of a performance run and record again at the end of the run and then calculate difference as total vol & non-vol ctx switches during the performance run.

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

Script is bit heavy, in my case process has around 2500 threads. Total time to collect ctx switches is around 10 seconds.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号