使用 'Microsoft Visual C++ 2013 Professional' 编译。
timer.h文件源码如下
#ifndef _TIMER_H_
#define _TIMER_H_
#include <string>
#include <sstream>
//#include <sys/time.h> //windows下的time.h中没有timeval定义
#include<windows.h> //windows下代替<sys/time.h>
#include<time.h> //windows下代替<sys/time.h>
using namespace std;
//windows下没有gettimeofday函数,从网上找的一个替代函数
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);
}
class timer {
public:
int gettimeofday(struct timeval *tp, void *tzp);
timer(string timer_name) {
name = timer_name;
total_time = 0;
calls = 0;
}
~timer() {}
void tic() {
struct timeval tv;
gettimeofday(&tv, NULL);
last_time = (double)tv.tv_sec + 1e-6*(double)tv.tv_usec;
calls++;
}
void toc() {
struct timeval tv;
gettimeofday(&tv, NULL);
double cur_time = (double)tv.tv_sec + 1e-6*(double)tv.tv_usec;
total_time += cur_time - last_time;
}
const char *msg() {
ostringstream oss;
oss << "timer '" << name
<< "' = " << total_time << " sec in "
<< calls << " call(s)";
return oss.str().c_str();
}
void mexPrintTimer() {
mexPrintf("timer '%s' = %f sec in %d call(s)\n", name.c_str(), total_time, calls);
}
double getTotalTime() {
return total_time;
}
private:
string name;
int calls;
double last_time;
double total_time;
}
#endif
这是你自己改变了源码吗?
对
public:
//int gettimeofday(struct timeval *tp, void *tzp);//注释掉
....
....
}; //加个分号
#endif
//VS2017编译通过
你的本意是想让timer类可以自由调用GetTimeOfDay这个函数是吧。
如果是这样的话,建议你把类里的声明更改一下:
1 int gettimeofday(struct timeval *tp, void *tzp); 2 //更改为 3 friend int gettimeofday(struct timeval *tp, void *tzp); 4 //如此便可以作为友元使用了,就像调用类内成员一样。 5 //并且友元函数在类外定义,更多的用法建议你去百度一下