使用clock和times来获取进程运行时间
源于linux系统编程手册
clock 用于获取CPU运行进程全部时间
times用于分开为用户CPU和系统CPU的运行时间
times的结构体
struct tms
sysconf 用于获取系统的配置
#include<stdio.h>
#include<time.h>
#include<sys/times.h>
#include<stdlib.h>
#include<unistd.h>
static void displayProcessTimes(const char *msg)
{
struct tms t;
clock_t clockTime;
static long clockTicks = 0;
if(msg != NULL )
{
printf("%s",msg);
}
if(clockTicks == 0)
{
clockTicks = sysconf(_SC_CLK_TCK);
if(clockTicks == -1)
{
perror("sysconf");
return ;
}
}
clockTime = clock();
if(clockTime == -1)
{
perror("clock");
return ;
}
printf("clock() returns : %ld clocks-per-sec(%.2f secs)\n",(long)clockTime,
(double)clockTime / CLOCKS_PER_SEC);
if(times(&t) == -1)
{
perror("times\n");
return ;
}
printf(" times() yields:user CPU=%.2f;system CPU:%.2f\n",
(double)t.tms_utime / clockTicks,
(double)t.tms_stime / clockTicks);
}
int main(int argc, char *argv[])
{
int numCalls , j;
printf("CLOCKS_PER_SEC = %ld sysconf(_SC_CLK_TCK)=%ld \n\n",(long)CLOCKS_PER_SEC,
sysconf(_SC_CLK_TCK));//获取时间的脉冲数
displayProcessTimes("At proram start:\n");
numCalls = (argc > 1) ? atoi(argv[1]) : 100000000;
for(j = 0 ; j < numCalls ; j++)
{
(void)getppid();
}
displayProcessTimes("After getppid() loop:\n");
exit(EXIT_SUCCESS);
return 0;
}