linux 中的 <sys/time.h> 中 有个函数可以获取当前时间,精确到 微秒 ----> gettimeofday()
例子:
 
使用时,定义两个 struct timeval 变量(通常 gettimeofday() 的第二个参数 设为 NULL),分别保存 代码测试 前后的时刻,最后相减,即可获取 代码运行时间 (可转换为自己需要的时间)。
例子:
 
#include <stdio.h>
#include <sys/time.h> // for gettimeofday()
#include <string.h>   // for memset()
int main()
{
    int i = 10000000;
    struct timeval start, end;  // define 2 struct timeval variables
    //-------------------------
    gettimeofday(&start, NULL); // get the beginning time
    //-------------------------
    
    // test code
    while(i)
    {
        i--;
    }
    //-------------------------
    gettimeofday(&end, NULL);  // get the end time
    //-------------------------
    
    long long total_time = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); // get the run time by microsecond
    printf("total time is %lld usn", total_time);
    total_time /= 1000; // get the run time by millisecond
    printf("total time is %lld msn", total_time);
}
测试结果:(centos 6.5, gcc 4.4.7)
total time is 49658 us
total time is 49 ms
测试结果:(CentOS 6.5, gcc 4.4.7)
total time is 49658 us
total time is 49 ms