c++ 杂项(1) 获取系统启动运行时间
1、获取系统启动运行时间
a、windows平台使用
ULONGLONG GetTickCount64(VOID);
示例:
#include <iostream>
#include <windows.h>
int main() {
std::cout << "系统运行时间: " << GetTickCount64() << " 毫秒" << std::endl;
return 0;
}
b、linux 平台使用
int clock_gettime (clockid_t __clock_id, struct timespec *__tp)
示例:
#include <stdio.h>
#include <time.h>
int main() {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
std::cout << "系统运行时间: " << (int64_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000) << " 毫秒" << std::endl;
return 0;
}
结合下, 以一个工具类封装:
#ifndef __XX_TOOL_H__
#define __XX_TOOL_H__
#include <stdint.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <time.h>
#endif
class XXTool {
public:
//系统运行时间
static int64_t GetTickCount() {
#ifdef _WIN32
return ::GetTickCount64();
#else
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (int64_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
#endif
}
};
#endif
惯例, 使用文心一言分析修正
您这段代码是一个用于获取系统运行时间的函数。它首先检查是否定义了_WIN32宏,如果是,则使用Windows API的GetTickCount64函数来获取高精度时间戳。如果未定义该宏(即代码运行在非Windows平台上),则使用clock_gettime函数获取当前时间,并计算出自系统启动以来的时间(以毫秒为单位)。
这段代码的主要目的是提供一种跨平台的方法来获取系统运行时间,无论是在Windows还是其他操作系统上。
以下是该代码的逐行解释:
- //系统运行时间: 这是一个注释,用于解释接下来的代码功能。
- static int64_t GetTickCount() {: 定义一个静态函数GetTickCount,该函数返回一个int64_t类型的时间戳。
- #ifdef _WIN32: 这是一个预处理指令,检查是否定义了_WIN32宏。
- return ::GetTickCount64();: 如果_WIN32宏已定义(即在Windows平台上),则调用Windows API的GetTickCount64函数来获取高精度时间戳,并返回。
- #else: 如果未定义_WIN32宏(即在非Windows平台上)。
- struct timespec ts;: 定义一个timespec结构体变量ts,用于存储时间信息。
- clock_gettime(CLOCK_MONOTONIC, &ts);: 使用clock_gettime函数获取当前时间,并存储在ts结构体中。这里使用的是CLOCK_MONOTONIC时钟,它是一个单调时钟,不受系统时间调整的影响。
- return (int64_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000);: 将获取的时间(秒和纳秒)转换为毫秒并返回。
- #endif: 结束条件编译块。
总结:该代码的目的是提供一种跨平台的方法来获取系统运行时间,根据不同的操作系统使用相应的方法来实现。在Windows上使用Windows API,在其他操作系统上使用clock_gettime函数。