测试函数执行时间;
#define WIN32 // 如果VC编译器定义WIN32 使用gettimeofday()
#include <time.h>
#ifdef WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif
#ifdef WIN32
int gettimeofday(struct timeval *tp, void *tzp)
{
time_t clock;
struct tm tm;
SYSTEMTIME wtm;
GetLocalTime(&wtm);
tm.tm_year = wtm.wYear - 1900;
tm.tm_mon = wtm.wMonth - 1;
tm.tm_mday = wtm.wDay;
tm.tm_hour = wtm.wHour;
tm.tm_min = wtm.wMinute;
tm.tm_sec = wtm.wSecond;
tm.tm_isdst = -1;
clock = mktime(&tm);
tp->tv_sec = clock;
tp->tv_usec = wtm.wMilliseconds * 1000;
return (0);
}
#endif /* WIN32 */
// 测试执行时间代码
timeval tv;
gettimeofday(&tv, NULL);
double cl = tv.tv_sec + (double)tv.tv_usec / 1000000;
//测试代码
gettimeofday(&tv, NULL);
cl = (tv.tv_sec + (double)tv.tv_usec / 1000000) - cl;
printf("\n执行时间 : %0.3f 秒\n", cl);
例如测试一个翻转字符代码:
void Reverse(char *word) // 适合C风格字符串反转函数
{ // 来源 C++ Primer Plus 第五章 forstr2.cpp -- reversing an array
char temp;
size_t i, j;
for (j = 0, i = strlen(word) - 1; j < i; --i, ++j) {
temp = word[i];
word[i] = word[j];
word[j] = temp;
}
}
int main()
{
using namespace std;
// 1KW 字符串反序函数测试,分别测试同样算法,string 和 C风格字符串的区别
// 测试执行时间代码
timeval tv;
gettimeofday(&tv, NULL);
double cl = tv.tv_sec + (double)tv.tv_usec / 1000000;
char cs[] = "0123456789abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i != 10000001; i++)
Reverse(cs);
cout << cs << endl;
gettimeofday(&tv, NULL);
cl = (tv.tv_sec + (double)tv.tv_usec / 1000000) - cl;
printf("\n执行时间 : %0.3f 秒\n", cl);
return 0;
}