前回の記事「組込みソフトウェア開発雑談(5): スレッドのCPU使用率」では、スレッドのCPU使用率を確認する方法を簡単に紹介しましたが、次に問題は、特定のプロセスまたはスレッドのCPU使用率を知りたいということです。どの機能が CPU 使用率を増加させたか知っていますか?
最も便利な方法は、perf ツールを使用することです。perf は、システムの全体的なパフォーマンスを分析できるだけでなく、Fenix プロセスのスレッド レベル、さらには関数やアセンブリのパフォーマンスも分析できるパフォーマンス分析ツールです。 perf の使い方についてはここでは紹介しませんので、興味のある方は Baidu からダウンロードしてください。
前回の記事のコードを参照すると、テストコードは次のとおりです。
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/prctl.h>
#include <math.h>
int test_sqrt()
{
double value = 0;
int i = 0;
for (i = 0; i < 1000000; i++)
value += sqrt(i*i*i*i);
return 0;
}
void* thread11(void* arg)
{
printf("----->thread11\n");
prctl(PR_SET_NAME, "thread11");
while(1)
{
test_sqrt();
sleep(1);
}
}
void* thread12(void* arg)
{
printf("----->thread12\n");
prctl(PR_SET_NAME, "thread12");
while(1)
{
usleep(1);
}
}
void* thread13(void* arg)
{
printf("----->thread13\n");
prctl(PR_SET_NAME, "thread13");
while(1)
{
usleep(100);
}
}
int main()
{
pthread_t thread[3];
int s32Ret = 0;
s32Ret = pthread_create(&thread[0], NULL, thread11, NULL);
printf("pthread_create, ret:%d\n", s32Ret);
sleep(1);
s32Ret = pthread_create(&thread[1], NULL, thread12, NULL);
printf("pthread_create, ret:%d\n", s32Ret);
sleep(1);
s32Ret = pthread_create(&thread[0], NULL, thread13, NULL);
printf("pthread_create, ret:%d\n", s32Ret);
sleep(1);
while(1)
{
sleep(1);
}
return 0;
}
コンパイルして実行ファイルを生成し、テストを実行します。
次のように、perf top コマンドを使用して、CPU クロックを最も占有する関数または命令を表示します。
上記フィールドのオーバーヘッドは全サンプルに占めるシンボルイベントの割合を示しており、プロセステストにおけるtest_sqrtがサンプルに占める割合が比較的高いことが分かります。
次のコマンドを使用して、プロセス テスト プロセスの状況を個別に分析できます。
#perf top -g -p 841
-g 呼び出し関係解析を有効にする -p テストのプロセス番号としてプロセス番号 841 を指定
上記と同様に、詳細については、「方向キー」を使用して test_sqrt を選択し、「Enter キー」を押して呼び出し関係を表示します。
上記のように、thread11 の test_sqrt 関数が比較的高い割合を占めていることがわかります。