工作场景:让用户根据接口查询系统各资源占用率
- 优化用户性能
传统代码:
传统代码
//main.cpp
#include <iostream>
#include "ServerInfoGetter.h"
#include <chrono>
#include <thread>
int main()
{
ServerInfoGetter getter;
ServerInfo info = getter.getInfo();
while (1) {
std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tp = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
long long currentTime = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch()).count();
if (currentTime - info.createTime >= 2000) {
info = getter.getInfo();
}
else {
// .....
}
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}
return 0;
}
//ServerInfoGetter.h
#include "ServerInfoGetter.h"
ServerInfo ServerInfoGetter::getInfo()
{
ServerInfo info;
info.cpu = 0.45;
info.mem = 0.23;
return info;
}
//
#pragma onServerInfoGetter.hce
#include "ServerInfo.h"
class ServerInfoGetter
{
public:
ServerInfo getInfo();
};
//ServerInfo.h
#pragma once
class ServerInfo
{
public:
ServerInfo();
float cpu;
float mem;
long long createTime;
};
//ServerInfo.cpp
#include "ServerInfo.h"
#include <chrono>
#include <thread>
ServerInfo::ServerInfo()
{
std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tp = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
createTime = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch()).count();
}
ServerInfoGetter::getInfo()
返回用户要查询的系统占用值- ServerInfo::ServerInfo封装了getinfo返回值的类型
ServerInfoGetter getter; ServerInfo info = getter.getInfo();
在死循环里面每两秒发送信息给用户,