经过查阅资料,浏览各大嵌入式开发论坛,总结得下面一些方法,各有利弊。首先我先介绍一下VxWorks的spyLib库提供的spy工具的实现原理。
Spy利用辅助定时器来产生中断,并且为每个任务维护一个计数器。然后记下被中断的任务,并且将该任务的计数器加一。经过一段时间后,每个任务的计数器反映了该任务占用CPU利用率的情况。很明显,这是利用抽样技术。并且得到的cpu利用率的准确程度取决于任务的持续性和周期性。
通过查找spyLib.h的文件,我们发现除了spy()函数外,还有一spyCommon函数,带一函数指针参数。推测函数指针类型为(int)(*p)(char * fmtStr,…)(经过验证确实如此)。所以可以写一自己的函数去接受spy需要打印的数据,Spy调用该函数按行打印结果。我们可以不断分析一行字符串来得到我们需要的结果。
int SpyPtnFunc(const char * fmtPtn,...)
{
char buf[128];
CPUUSAGEDATAMSG data;
va_list vl;
va_start(vl,fmtPtn);
vsprintf(buf,fmtPtn,vl); //得到一行字符串。
va_end(vl);
//分析buf,得到一个任务的Cpu的使用情况。
return 0;
}
另外一种方法是利用一特殊任务,该任务的优先级比系统中的所有任务的优先级都低,该任务是死循环,该任务的目的就是消耗cpu资源,占用cpu空闲时间,因为当系统中其它任务都被挂其时,该任务才能得到cpu的使用权。假设一段时间total内,该任务的运行时间为idle,cpu利用率的计算公式为(total-idle)%total。这一种方法实现起来很简单,但是它只能算得整个系统的cpu使用情况,不能得到单个任务的cpu使用情况!同时它会使cpu满负荷工作。源代码如下
#include "VxWorks.h"
#include "semLib.h"
#include "taskLib.h"
#define SECONDS_TO_BURN 60
typedef struct cpuUsage {
SEM_ID startSem;
int didNotComplete;
unsigned long ticksNoContention;
int nBurnNoContention;
unsigned long ticksNow;
int nBurnNow;
double usage;
} cpuUsage;
static cpuUsage *pcpuUsage=0;
static double cpuBurn()
{
int i;
double result = 0.0;
for(i=0;i<5; i++) result += sqrt((double)i);
return(result);
}
static void cpuUsageTask()
{
while(TRUE) {
int i;
unsigned long tickStart,tickEnd;
semTake(pcpuUsage->startSem,WAIT_FOREVER);
pcpuUsage->ticksNow=0;
pcpuUsage->nBurnNow=0;
tickStart = tickGet();
for(i=0; i< pcpuUsage->nBurnNoContention; i++) {
cpuBurn();
pcpuUsage->ticksNow = tickGet() - tickStart;
++pcpuUsage->nBurnNow;
}
tickEnd = tickGet();
pcpuUsage->didNotComplete = FALSE;
pcpuUsage->ticksNow = tickEnd - tickStart;
}
}
double getCpu()
{
if(pcpuUsage->didNotComplete && pcpuUsage->nBurnNow==0) {
pcpuUsage->usage = 0.0;
} else {
double temp;
double ticksNow,nBurnNow;
ticksNow = (double)pcpuUsage->ticksNow;
nBurnNow = (double)pcpuUsage->nBurnNow;
ticksNow *= (double)pcpuUsage->nBurnNoContention/nBurnNow;
temp = ticksNow - (double)pcpuUsage->ticksNoContention;
temp = 100.0 * temp/ticksNow;
if(temp<0.0 || temp>100.0) temp=0.0; /*handle tick overflow*/
pcpuUsage->usage = temp;
}
pcpuUsage->didNotComplete = TRUE;
semGive(pcpuUsage->startSem);
printf("CPU usage:%f/r/n",pcpuUsage->usage);
return(pcpuUsage->usage);
}
void cpuUsageInit(void)
{
unsigned long tickStart,tickNow;
int nBurnNoContention=0;
int ticksToWait;
ticksToWait = SECONDS_TO_BURN*sysClkRateGet();
pcpuUsage = calloc(1,sizeof(cpuUsage));
tickStart = tickGet();
/*wait for a tick*/
while(tickStart==(tickNow = tickGet())) {;}
tickStart = tickNow;
while(TRUE) {
if((tickGet() - tickStart)>=ticksToWait) break;
cpuBurn();
nBurnNoContention++;
}
pcpuUsage->nBurnNoContention = nBurnNoContention;
pcpuUsage->startSem = semBCreate (SEM_Q_FIFO,SEM_EMPTY);
pcpuUsage->ticksNoContention = ticksToWait;
pcpuUsage->didNotComplete = TRUE;
taskSpawn("cpuUsageTask",255,VX_FP_TASK,1000,(FUNCPTR)cpuUsageTask,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
以上两种方法我都实现了,工作的很正常!