获得程序运行时间

12 篇文章 0 订阅

windows (http://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx)

#include <windows.h>
long long milliseconds_now() {
    static LARGE_INTEGER s_frequency;
    static BOOL s_use_qpc = QueryPerformanceFrequency(&s_frequency);
    if (s_use_qpc) {
        LARGE_INTEGER now;
        QueryPerformanceCounter(&now);
        return (1000LL * now.QuadPart) / s_frequency.QuadPart;
    } else {
        return GetTickCount();
    }
}

int main()
{
    long long start = milliseconds_now();
    // Your run code here
    long long elapsed = milliseconds_now() - start;
}

mac/linux下命令行执行时前面加上time,或者

#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
    struct timeval start, end;
    long mtime, seconds, useconds;
    gettimeofday(&start, NULL);

   // Your code here

   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;
}

根据文档,clock精度要低一些。QueryPerformanceFrequency/gettimeofday是高精度的,更高精度的x86上有intel cpu指令。

https://software.intel.com/en-us/articles/best-timing-function-for-measuring-ipp-api-timing

The C standard does not say anything about the granularity of clock() - a compiler can have it check time once a second and increment the variable by CLOCKS_PER_SEC. This means it is possible that, depending on different compiler implementation, you can get zero, CLOCKS_PER_SEC, CLOCKS_PER_SEC * 2 and so on, never getting any intermediate value. Don't use clock() if you need high granularity.

引用另外的说法,未实验
http://www.cnblogs.com/krythur/archive/2013/02/25/2932647.html
http://blog.csdn.net/russell_tao/article/details/7185588

clock 函数的返回值类型是clock_t,它除以CLOCKS_PER_SEC来得出时间,一般用两次clock函数来计算进程自身运行的时间.

ANSI clock有三个问题:
1)如果超过一个小时,将要导致溢出.
2)函数clock没有考虑CPU被子进程使用的情况.
3)也不能区分用户空间和内核空间.

所以clock函数在linux系统上变得没有意义.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值