c++测量程序运行时间

头文件

​ #include

获得当前时间函数

查看源码得知

/* Time used by the program so far (user time + system time).
   The result / CLOCKS_PER_SECOND is program time in seconds.  */
extern clock_t clock (void) __THROW;

也就是 clock();,默认是毫秒

结果除以 CLOCKS_PER_SECOND得到秒

clock_t这个把他当作最长值处理就行

获得一段代码的时间

#include <iostream>
#include <string>
#include <ctime>
int main()
{
    clock_t start = clock();
    std::cout << "run" << std::endl;
    clock_t end = clock();
    std::cout << "start " << start <<  std::endl;
    std::cout << "end " << end <<  std::endl;

    std::cout << "ms is " << (end - start) <<  std::endl;
    std::cout << "s is " << (end - start)/((clock_t) 1000) <<  std::endl;

    return 0;
}

额外

clock() 返回cpu占用时间,而调用 sleep() 休眠时并不会占用CPU时间

clock() 中 CLOCKS_PER_SEC 在Linux下为 1,000,000 , 而在Windows 下为 1000

posted @ 2021-05-26 09:56  make_wheels  阅读(226)  评论(0编辑  收藏  举报