您的位置:首页 > 编程语言 > C语言/C++

C++ 计算 代码运行时间的 几种方法 .

2013-11-11 14:18 1126 查看
有许多专门的测试工具,测试的准确性很高,本文说的是一些简单的测试方法,这些方法多数是记录CPU的运行时间,没有考虑操作系统的分时复用,不过不太严格的情况都可一用。

1. #include <time.h>

long start=clock(),end(0);

//ToDo:process code

end=clock();

long result=(end-start)/1000

2. windows 平台

#include <windows.h>

double start=getticktime(),end(0);

//ToDo:process code

end=getticktime();

double result=end-start;

3.windows 平台

#include <windows.h>

LARGE_INTEGER frequency,start,end;

QueryPerformanceFrequency(&frequency);

QueryPerformanceCounter(&start);

//ToDO:process code

QueryPerformanceCounter(&end);

double d = (double)(end.QuadPart - start.QuadPart) / (double)frequency.QuadPart * 1000.0;

4.根据线程而来的

CThreadTime ElapsedTime;

ElapsedTime.BeginGetElapsedTime();

//TODO: Your performance code

int nThreadTine = ElapsedTime.EndGetElapsedTime();

该类的实现如下:

// This class is for getting the elapsed thread time of the CPU, the unit is ms

// the usage is:

//

// CThreadTime ElapsedTime;

// ElapsedTime.BeginGetElapsedTime();

// TODO: Your performance code

// int nThreadTine = ElapsedTime.EndGetElapsedTime();

//

#include <Windows.h>

class CThreadTime

{

public:

void BeginGetElapsedTime();

__int64 EndGetElapsedTime();

private:

__int64 FileTimeToQuadWord(PFILETIME pft);

private:

FILETIME ftKernelTimeStart;

FILETIME ftKernelTimeEnd;

FILETIME ftUserTimeStart;

FILETIME ftUserTimeEnd;

FILETIME ftDummy;

};

// Get the time elapsed since the thread start

inline void CThreadTime::BeginGetElapsedTime()

{

GetThreadTimes(GetCurrentThread(), &ftDummy, &ftDummy, &ftKernelTimeStart, &ftUserTimeStart);

}

// Calculate the time elapsed

inline __int64 CThreadTime::EndGetElapsedTime()

{

GetThreadTimes(GetCurrentThread(), &ftDummy, &ftDummy, &ftKernelTimeEnd, &ftUserTimeEnd);

__int64 qwKernelTimeElapsed = FileTimeToQuadWord(&ftKernelTimeEnd) - FileTimeToQuadWord(&ftKernelTimeStart);

__int64 qwUserTimeElapsed = FileTimeToQuadWord(&ftUserTimeEnd) - FileTimeToQuadWord(&ftUserTimeStart);

// Get total time duration by adding the kernel and user times.

// the default is 100ns, so we convert it to ms

return (qwKernelTimeElapsed + qwUserTimeElapsed) / 10000;

}

inline __int64 CThreadTime::FileTimeToQuadWord(PFILETIME pft)

{

return (Int64ShllMod32(pft->dwHighDateTime, 32) | pft->dwLowDateTime);

}

////////////////////////////////

帖个算法给你:

// This class is for getting the elapsed thread time of the CPU, the unit is ms

// the usage is:

//

// CThreadTime ElapsedTime;

// ElapsedTime.BeginGetElapsedTime();

// TODO: Your performance code

// int nThreadTine = ElapsedTime.EndGetElapsedTime();

//

#include <Windows.h>

class CThreadTime

{

public:

void BeginGetElapsedTime();

__int64 EndGetElapsedTime();

private:

__int64 FileTimeToQuadWord(PFILETIME pft);

private:

FILETIME ftKernelTimeStart;

FILETIME ftKernelTimeEnd;

FILETIME ftUserTimeStart;

FILETIME ftUserTimeEnd;

FILETIME ftDummy;

};

// Get the time elapsed since the thread start

inline void CThreadTime::BeginGetElapsedTime()

{

GetThreadTimes(GetCurrentThread(), &ftDummy, &ftDummy, &ftKernelTimeStart, &ftUserTimeStart);

}

// Calculate the time elapsed

inline __int64 CThreadTime::EndGetElapsedTime()

{

GetThreadTimes(GetCurrentThread(), &ftDummy, &ftDummy, &ftKernelTimeEnd, &ftUserTimeEnd);

__int64 qwKernelTimeElapsed = FileTimeToQuadWord(&ftKernelTimeEnd) - FileTimeToQuadWord(&ftKernelTimeStart);

__int64 qwUserTimeElapsed = FileTimeToQuadWord(&ftUserTimeEnd) - FileTimeToQuadWord(&ftUserTimeStart);

// Get total time duration by adding the kernel and user times.

// the default is 100ns, so we convert it to ms

return (qwKernelTimeElapsed + qwUserTimeElapsed) / 10000;

}

inline __int64 CThreadTime::FileTimeToQuadWord(PFILETIME pft)

{

return (Int64ShllMod32(pft->dwHighDateTime, 32) | pft->dwLowDateTime);

}

最后出来的是毫秒精度,当然也可以有更高精度,只要在那个10000上做文章就ok了。

/////////////////////////////////

Unix™ Systems Programming: Communication, Concurrency, and Threads

9.1.5 Contrasting elapsed time to processor time

#include <sys/times.h>

clock_t times(struct tms *buffer);

The struct tms structure contains at least the following members.

clock_t tms_utime; /* user CPU time of process */

clock_t tms_stime; /* system CPU time on behalf of process */

clock_t tms_cutime /* user CPU time of process and terminated children */

clock_t tms_cstime; /* system CPU time of process and terminated children */

程序Program 9.4 cpufraction.c及Program 9.5 timechild.c

分别说明了如何计算程序中某个函数的CPU时间和子程序的执行时间。

这2个例子或许对你有帮助。

9.3、9.5节的内容也可参考,算是另外2种解决方法。

Program 9.4 cpufraction.c

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <sys/times.h>

void function_to_time(void);

int main(void) {

double clockticks, cticks;

clock_t tcend, tcstart;

struct tms tmend, tmstart;

if ((clockticks = (double) sysconf(_SC_CLK_TCK)) == -1) {

perror("Failed to determine clock ticks per second");

return 1;

}

printf("The number of ticks per second is %f\n", clockticks);

if (clockticks == 0) {

fprintf(stderr, "The number of ticks per second is invalid\n");

return 1;

}

if ((tcstart = times(&tmstart)) == -1) {

perror("Failed to get start time");

return 1;

}

function_to_time();

if ((tcend = times(&tmend)) == -1) {

perror("Failed to get end times");

return 1;

}

cticks = tmend.tms_utime + tmend.tms_stime

- tmstart.tms_utime - tmstart.tms_stime;

printf("Total CPU time for operation is %f seconds\n",cticks/clockticks);

if ((tcend <= tcstart) || (tcend < 0) || (tcstart < 0)) {

fprintf(stderr, "Tick time wrapped, couldn't calculate fraction\n);

return 1;

}

printf("Fraction of CPU time used is %f\n", cticks/(tcend - tcstart));

return 0;

}

复制代码

Program 9.5 timechild.c

#include <errno.h>

#include <stdio.h>

#include <unistd.h>

#include <sys/times.h>

#include <sys/types.h>

#include <sys/wait.h>

#include "restart.h"

int main(int argc, char *argv[]) {

pid_t child;

double clockticks;

double cticks;

struct tms tmend;

if (argc < 2){ /* check for valid number of command-line arguments */

fprintf (stderr, "Usage: %s command\n", argv[0]);

return 1;

}

if ((child = fork()) == -1) {

perror("Failed to fork");

return 1;

}

if (child == 0) { /* child code */

execvp(argv[1], &argv[1]);

perror("Child failed to execvp the command");

return 1;

}

if (r_wait(NULL) == -1) { /* parent code */

perror("Failed to wait for child");

return 1;

}

if (times(&tmend) == (clock_t)-1) {

perror("Failed to get end time");

return 1;

}

if ((clockticks = (double) sysconf(_SC_CLK_TCK)) == -1) {

perror("Failed to determine clock ticks per second");

return 1;

}

if (clockticks == 0) {

fprintf(stderr, "Invalid number of ticks per second\n");

return 1;

}

cticks = tmend.tms_cutime + tmend.tms_cstime

- tmend.tms_utime - tmend.tms_stime;

printf("%s used %ld clock ticks or %f seconds\n", argv[1],

(long)cticks, cticks/clockticks);

return 0;

}

复制代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: