需要用到 time.h
//time.cpp
#include <time.h>
#include <iostream>
int main()
{
clock_t t;
long n = 1500 * 1500 ;
std::cout << "Begin clock" << std::endl;
//第一次调用:记录程序从开始执行到本次调用经历的时间
t = clock();
while(n--);
std::cout << "Second clock" << std::endl;
//第二次调用:从程序开始到本次调用的时间与第一次调用的时间差即为while()用时
t = clock() - t;
std::cout << "t = " << t << std::endl;
//这里需注意,clock_t 的变量并不是以s为单位的时间,需要进行转换
float time = (float)t * 1000 / CLOCKS_PER_SEC;
std::cout << "It takes " << time << "ms" << std::endl;
return 0;
}
结果: