在Windows上,clock()以毫秒为单位返回时间,但是在我正在处理的这个Linux机器上,它将它舍入到最接近的1000,因此精度仅为"秒"级别而不是毫秒级别.
我找到了一个使用QTime该类的Qt解决方案,实例化一个对象并调用start()它然后调用elapsed()以获得经过的毫秒数.
我有点幸运,因为我开始使用Qt,但我想要一个不依赖第三方库的解决方案,
有没有标准的方法来做到这一点?
UPDATE
请不要推荐Boost ..
如果Boost和Qt可以做到这一点,那肯定不是魔术,必须有他们正在使用的标准!
CTT*_*CTT 137
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
    struct timeval start, end;
    long mtime, seconds, useconds;    
    gettimeofday(&start, NULL);
    usleep(2000);
    gettimeofday(&end, NULL);
    seconds  = end.tv_sec  - start.tv_sec;
    useconds = end.tv_usec - start.tv_usec;
    mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
    printf("Elapsed time: %ld milliseconds\n", mtime);
    return 0;
}
Joh*_*itb 57
请注意,clock并不能衡量挂钟的时间.这意味着如果您的程序需要5秒钟,clock则不一定会测量5秒,但可能会更多(您的程序可以运行多个线程,因此可能会消耗比实时更多的CPU)或更少.它测量所用CPU时间的近似值.要查看差异,请考虑此代码
#include <iostream>
#include <ctime>
#include <unistd.h>
int main() {
    std::clock_t a = std::clock();
    sleep(5); // sleep 5s
    std::clock_t b = std::clock();
    std::cout << "difference: " << (b - a) << std::endl;
    return 0;
}
它在我的系统上输出
$ difference: 0
因为我们所做的就是睡觉而不使用任何CPU时间!然而,使用gettimeofday我们得到我们想要的东西(?)
#include <iostream>
#include <ctime>
#include <unistd.h>
#include <sys/time.h>
int main() {
    timeval a;
    timeval b;
    gettimeofday(&a, 0);
    sleep(5); // sleep 5s
    gettimeofday(&b, 0);
    std::cout << "difference: " << (b.tv_sec - a.tv_sec) << std::endl;
    return 0;
}
我的系统输出
$ difference: 5
如果您需要更高的精度但想要获得CPU时间,那么您可以考虑使用该getrusage功能.
Ada*_*wes 37
您可以在方法的开头和结尾使用gettimeofday,然后区分两个返回结构.您将获得如下结构:
struct timeval {
  time_t tv_sec;
  suseconds_t tv_usec;
}
Ano*_*ous 18
我还推荐Boost提供的工具.无论是提到的Boost Timer,还是Boost.DateTime中的东西,或者沙盒中都有新的提议库 - Boost.Chrono:这最后一个将是Timer的替代品,并将具有以下功能:
durationtime_pointsystem_clockmonotonic_clockhigh_resolution_clocktimer,带有typedef:
system_timermonotonic_timerhigh_resolution_timerprocess_clock捕获实际,用户CPU和系统CPU时间.process_timer,捕获经过的实际,用户CPU和系统CPU时间.run_timer,方便的报告| process_timer | 结果.Chr*_*ord 13
我Timer根据CTT的答案写了一堂课.它可以通过以下方式使用:
Timer timer = Timer();
timer.start();
/* perform task */
double duration = timer.stop();
timer.printTime(duration);
这是它的实现:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
using namespace std;
class Timer {
private:
    timeval startTime;
public:
    void start(){
        gettimeofday(&startTime, NULL);
    }
    double stop(){
        timeval endTime;
        long seconds, useconds;
        double duration;
        gettimeofday(&endTime, NULL);
        seconds  = endTime.tv_sec  - startTime.tv_sec;
        useconds = endTime.tv_usec - startTime.tv_usec;
        duration = seconds + useconds/1000000.0;
        return duration;
    }
    static void printTime(double duration){
        printf("%5.6f seconds\n", duration);
    }
};
如果您不需要将代码移植到旧的unices,则可以使用clock_gettime(),这将为您提供以纳秒为单位的时间(如果您的处理器支持该分辨率).它是POSIX,但是从2001年开始.