在Linux中,毫秒级时间戳可以通过以下几种方式存储:
gettimeofday
函数获取纳秒级时间戳,然后除以1000得到毫秒级时间戳。示例代码如下:#include <sys/time.h>
#include <stdio.h>
long long get_millisecond_timestamp() {
struct timeval tv;
gettimeofday(&tv, NULL);
return (long long)tv.tv_sec * 1000 + (long long)tv.tv_usec / 1000;
}
int main() {
long long timestamp = get_millisecond_timestamp();
printf("Millisecond timestamp: %lld\n", timestamp);
return 0;
}
std::chrono
库(C++)获取纳秒级时间戳,然后将其转换为毫秒级时间戳。示例代码如下:#include <iostream>
#include <chrono>
long long get_millisecond_timestamp() {
auto now = std::chrono::high_resolution_clock::now();
auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
return (long long)nanoseconds / 1000000;
}
int main() {
long long timestamp = get_millisecond_timestamp();
std::cout << "Millisecond timestamp: " << timestamp << std::endl;
return 0;
}
将毫秒级时间戳存储为整数或浮点数。例如,可以使用long long
类型存储毫秒级时间戳,范围从-9223372036854775808到9223372036854775807。或者使用double
类型存储毫秒级时间戳,范围从-1.7976931348623157e+308到1.7976931348623157e+308。
将毫秒级时间戳存储为字符串。可以使用std::to_string
函数将毫秒级时间戳转换为字符串,然后将其存储在文件或数据库中。例如:
#include <iostream>
#include <string>
std::string get_millisecond_timestamp_str() {
auto now = std::chrono::high_resolution_clock::now();
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
return std::to_string(milliseconds);
}
int main() {
std::string timestamp_str = get_millisecond_timestamp_str();
std::cout << "Millisecond timestamp string: " << timestamp_str << std::endl;
return 0;
}
这些方法可以根据实际需求选择使用。