学习进程时间获取的笔记

使用clock和times来获取进程时间
源于linux系统编程手册

#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;
}

上一篇:C/C++中的日期和时间 TIME_T与STRUCT TM转换


下一篇:WinForm C# 获取屏幕真实分辨率