获得程序运行时间

来源:互联网 发布:怎么关闭百度推荐 知乎 编辑:程序博客网 时间:2024/06/11 04:54

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系统上变得没有意义.

0 0
原创粉丝点击