【发布时间】:2010-06-29 08:50:55
【问题描述】:
我试过clock_gettime(CLOCK_REALTIME) 和gettimeofday() 都没有运气 - 而最基本的,比如clock(),什么返回0给我(?)。
但他们都没有计算睡眠时间。我不需要高分辨率计时器,但我需要一些东西来获取以毫秒为单位的经过时间。
编辑:最终程序:
#include <iostream>
#include <string>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
using namespace std;
// Non-system sleep (wasting cpu)
void wait ( int seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
}
int show_time() {
timeval tv;
gettimeofday(&tv, 0);
time_t t = tv.tv_sec;
long sub_sec = tv.tv_usec;
cout<<"t value: "<<t<<endl;
cout<<"sub_sec value: "<<sub_sec<<endl;
}
int main() {
cout<<show_time()<<endl;
sleep(2);
cout<<show_time()<<endl;
wait(2);
cout<<show_time()<<endl;
}
【问题讨论】: