1、统计程序运行时间
#include <sys/time.h>
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
struct timeval start_time, end_time;
gettimeofday(&start_time, NULL);
sleep(5);
gettimeofday(&end_time, NULL);
//cost_time的单位是微秒
long cost_time = (end_time.tv_sec - start_time.tv_sec) * 1000000 + (end_time.tv_usec - start_time.tv_usec);
std::cout << "total cost time : " << cost_time/1000000 << endl;
return 0;
}
2、分割字串函数
// 对字符串根据指定的单个字符进行拆分,返回分割后的字符串数组
vector<string> SplitString(const string& obj_string, char character)
{
vector<string> string_vector;
if (obj_string.size() == 0)
{
return string_vector;
}
size_t pos_begin = 0;
size_t pos_end = 0;
bool last_obj_store = true;
while (pos_end != string::npos)
{
pos_begin = pos_end;
pos_end = obj_string.find(character, pos_begin);
if (pos_begin == pos_end)
{
pos_end += 1;
continue;
}
if (pos_end == string::npos)
{
string_vector.push_back(obj_string.substr(pos_begin, obj_string.length() - pos_begin));
break;
}
string_vector.push_back(obj_string.substr(pos_begin, pos_end - pos_begin));
pos_end += 1;
}
return string_vector;
}
3、格式化字符串
#include <iostream>
#include <sstream>
#include <string>
int main(int argc, char const *argv[])
{
string value = "hello";
int num = 3;
stringstream fmt;
fmt << "test string: " << value << ". test number: " << num;
string target_string = fmt.str();
std::cout << target_string << std::endl;
return 0;
}
4、时间戳和根据时间戳生成随机指定长度字符串
#include <iostream>
#include <sys/time.h>
#include <string>
using namespace std;
// 获取固定格式、固定长度的日期时间
string GetTimestamp()
{
time_t now = time(0); // 返回系统的当前日历时间,自 1970 年 1 月 1 日以来经过的秒数
tm *datetime = localtime(&now); // 返回一个指向表示本地时间的 tm 结构的指针。
// struct tm {
// int tm_sec; // 秒,正常范围从 0 到 59,但允许至 61
// int tm_min; // 分,范围从 0 到 59
// int tm_hour; // 小时,范围从 0 到 23
// int tm_mday; // 一月中的第几天,范围从 1 到 31
// int tm_mon; // 月,范围从 0 到 11
// int tm_year; // 自 1900 年起的年数
// int tm_wday; // 一周中的第几天,范围从 0 到 6,从星期日算起
// int tm_yday; // 一年中的第几天,范围从 0 到 365,从 1 月 1 日算起
// int tm_isdst; // 夏令时
// }
char str[100];
strftime(str, sizeof(str), "%Y%m%d%H%M%S", datetime);
string timestamp(str);
return timestamp;
}
// 根据时间戳生成指定长度随机字符串
string GetRandomString(int len)
{
struct timeval tv; // 保存时间信息
// struct timeval{
// long tv_sec; /* 返回的秒数是从1970年1月1日0时0分0秒开始到现在经历了多少秒*/
// long tv_usec; /* 微妙1e-6s */
// };
gettimeofday(&tv, nullptr); // 把时间包装为一个结构体返回。第一个参数保存秒、微妙,第二个参数保存时区
long sec = tv.tv_sec; // 秒
long usec = tv.tv_usec;
long million_second = tv.tv_sec * 1000 + tv.tv_usec/1000; // 毫秒
long micro_second = long(sec * 1e6 + usec); // 微妙
string ascii = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int length = ascii.size();
string target = "";
srand(micro_second); // 设置随机数生成种子
for (int i = 0; i < len; i++)
{
// rand()回0~RAND_MAX之间的随机数,整数
// random() 返回一个0~num-1之间的随机数,长整型
target += ascii[rand()%length];
}
return target;
}
int main()
{
std::cout << GetTimestamp() << std::endl;
std::cout << GetRandomString(30) << std::endl;
return 0;
}