Aug 22

Linux下取得精确的时间,精确到10^(-6)秒 不指定

felix021 @ 2008-8-22 02:39 [IT » 操作系统] 评论(0) , 引用(0) , 阅读(7299) | Via 本站原创 | |
因为需要测试算法的效率,所以专门找了一下在Linux下C/C++如何取得精确的时间来进行判断。
有两个办法,
1. 调用系统命令data +%s.%N,可以取得当前的Unix时间戳,格式为 秒数.毫秒数
FILE *pipe = popen("data +%s.%N", "r");
fscanf(pipe, "%d.%d", &s, &ns);
这样就取得了精确的时间。
2. 使用gettimeofday()函数
struct timeval { long tv_sec, tv_usec; }; //这个结构体保存秒数和毫秒数(0~1000000)
int gettimeofday(struct timeval *tv,struct timezone *tz); //调用时tz一般用NULL代替

下面对第二种方法给出样例程序:Linux下测试程序运行时间的一个类

#include<iostream>
#include<sys/time.h>
using namespace std;
struct timer{
    public:
    struct timeval begin, end;
    timer(){ gettimeofday(&begin, NULL); }
    void start(){ gettimeofday(&begin, NULL); }
    void finish(){ gettimeofday(&end, NULL); }
    friend inline ostream & operator<<(ostream &os, timer &a){
        double use = 1000000 * (a.end.tv_sec - a.begin.tv_sec) + a.end.tv_usec - a.begin.tv_usec;
        use /= 1000000.0;
        os << use;
        return os;
    }
};

int main(){
    timer timer1;
    timer1.start();
    for(int i = 0; i < 100000000; i++);
    timer1.finish();
    cout << timer1;
    return 0;
}




欢迎扫码关注:




转载请注明出自 ,如是转载文则注明原出处,谢谢:)
RSS订阅地址: https://www.felix021.com/blog/feed.php
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   *非必须
网址   电邮   [注册]