muduo EventLoop有三个定时器接口函数
class EventLoop :boost::noncopyable {
TimerId runAt(const Timestamp&time, const TimerCallback&cb);
//在指定的时间调用 TimerCallback
TimerId runAfter(const Timestamp&time, const TimerCallback&cb);
//等一段时间 TimerCallback
TimerId runEvery(const Timestamp&time, const TimerCallback&cb);
};
在每个统计周期打印吞吐量 AtomicInt64为原子操作,read出多少的字节
class DiscardServer
{
public:
DiscardServer(EventLoop* loop, const InetAddress& listenAddr)
: server_(loop, listenAddr, "DiscardServer"),
oldCounter_(0),
startTime_(Timestamp::now())
{
server_.setConnectionCallback(
boost::bind(&DiscardServer::onConnection, this, _1));
server_.setMessageCallback(
boost::bind(&DiscardServer::onMessage, this, _1, _2, _3));
server_.setThreadNum(numThreads);
loop->runEvery(3.0, boost::bind(&DiscardServer::printThroughput, this));
}
void printThroughput()
{
Timestamp endTime = Timestamp::now();
int64_t newCounter = transferred_.get();
int64_t bytes = newCounter - oldCounter_;
int64_t msgs = receivedMessages_.getAndSet(0);
double time = timeDifference(endTime, startTime_);
printf("%4.3f MiB/s %4.3f Ki Msgs/s %6.2f bytes per msg\n",
static_cast<double>(bytes)/time/1024/1024,
static_cast<double>(msgs)/time/1024,
static_cast<double>(bytes)/static_cast<double>(msgs));
oldCounter_ = newCounter;
startTime_ = endTime;
}
TcpServer server_;
AtomicInt64 transferred_;
AtomicInt64 receivedMessages_;
int64_t oldCounter_;
Timestamp startTime_;
};