clock()
C系统调用方法,所需头文件ctime/time.h,即windows和linux都可以使用。
1、clock()返回类型为clock_t类型
2、clock_t实际为long 类型, typedef long clock_t
3、clock() 函数,返回从 开启这个程序进程 到 程序中调用clock()函数 时之间的CPU时钟计时单元(clock tick)数(挂钟时间),返回单位是毫秒
4、可以用常量CLOCKS_PER_SEC, 这个常量表示每一秒(per second)有多少个时钟计时单元
1 2 3 4 5 6 7 8 9 10
| #include <time.h> int main() { clock_t start,end; start = clock();
fun()
end = clock(); std::cout<<"time = "<<double(end-start)/CLOCKS_PER_SEC<<"s"<<std::endl; }
|
C++11 std::chrono时间
1 2 3 4 5 6 7 8 9 10
| #include <chrono>
auto start = std::chrono::steady_clock::now();
auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; std::cout << "It took " << elapsed_seconds.count() << " seconds.";
|
秒数转时间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| bool IsLeap(int year) { if (year > 1970 && year < 9999) { if (year % 400 == 0 || year % 100 != 0 && year % 4 == 0) return true; } return false; }
std::string TimeToDate(int64_t time) { const char m_all_d[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int64_t total_day = time / (60 * 60 * 24); int year = 1970, month = 1, day = 1;
while (year < 9999) { const int y_all_d = IsLeap(year) ? 366 : 365;
if (total_day < y_all_d) {
for (month = 1; month <= 12 && total_day > m_all_d[month - 1]; month++) {
if (month == 2 && IsLeap(year)) total_day -= 29; else total_day -= m_all_d[month - 1]; } day += total_day; break; } else { total_day -= y_all_d; year++; } }
return std::to_string(year) + '-' + std::to_string(month) + '-' + std::to_string(day) + "-" + std::to_string((time % (3600 * 24)) / 3600); }
|