为了找到下面给出的代码的执行时间,我写了一个Timer类.
Timer::StartTimer();
DoOperation();
cout<<"Time elapsed: "<<Timer::GetTime();
Run Code Online (Sandbox Code Playgroud)
我得到的错误是startTime和endTime未定义.我无法解决问题.你能帮忙吗?
档案文件:timer.h
#include <sys/time.h>
class Timer
{
static timeval startTime, endTime;
public:
static void StartTimer();
static long int GetTime();
};
Run Code Online (Sandbox Code Playgroud)
文件:Timer.cc
#include "Timer.h"
void Timer::StartTimer()
{
gettimeofday(&startTime, NULL);
}
long int Timer::GetTime()
{
long int seconds, useconds, mtime;
gettimeofday(&endTime, NULL);
seconds = endTime.tv_sec - startTime.tv_sec;
useconds = endTime.tv_usec - startTime.tv_usec;
mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
return(mtime);
}
Run Code Online (Sandbox Code Playgroud)
在timer.cc中你需要:
timeval Timer::startTime;
timeval Timer::endTime;
Run Code Online (Sandbox Code Playgroud)
请参阅此常见问题
正如其他人已经指出的那样,尽管将这一切设为静态是"不寻常"的设计,但如果您尝试在多个位置同时使用此代码,则可能会导致问题.可能你想让它们都不是静态的,并且当你使用它时有一个实例.
| 归档时间: |
|
| 查看次数: |
388 次 |
| 最近记录: |