#include <iostream>
#include <stdint.h>
#include <unistd.h>
#include <signal.h>
using namespace std;
#define CARRY_BIT (1024)
#define NEED_CARRY(x) (x > CARRY_BIT)?(true):(false)
#define CARRY(x, y) do { \
if (NEED_CARRY(x)) { \
y = y + 1; \
x = 0; \
} \
} while (0)
class Count {
public:
Count()
:bytes_(0), KBytes_(0), MBytes_(0), GBytes_(0), TBytes_(0)
{
}
void Add(uint64_t bytes)
{
bytes_ += bytes;
CARRY(bytes_, KBytes_);
CARRY(KBytes_, MBytes_);
CARRY(MBytes_, GBytes_);
CARRY(GBytes_, TBytes_);
}
void Show(void)
{
cout << TBytes_ << "TB, "
<< GBytes_ << "GB, "
<< MBytes_ << "MB, "
<< KBytes_ << "KB, "
<< bytes_ << "Byte" << endl;
}
private:
uint64_t bytes_;
uint64_t KBytes_;
uint64_t MBytes_;
uint64_t GBytes_;
uint64_t TBytes_;
};
Count count;
void handle_alarm(int signal)
{
if (signal == SIGALRM) {
count.Show();
}
alarm(1);
}
void test(void)
{
signal(SIGALRM, handle_alarm);
alarm(1);
while (1) {
count.Add(1);
}
}
int main(int argc, char *const argv[])
{
test();
return 0;
}
结果:
0TB, 297GB, 492MB, 869KB, 534Byte
0TB, 297GB, 635MB, 995KB, 1003Byte
0TB, 297GB, 778MB, 812KB, 485Byte
0TB, 297GB, 921MB, 880KB, 832Byte
0TB, 298GB, 38MB, 1014KB, 339Byte
0TB, 298GB, 181MB, 123KB, 832Byte
0TB, 298GB, 324MB, 62KB, 1003Byte
0TB, 298GB, 467MB, 216KB, 189Byte
0TB, 298GB, 610MB, 321KB, 102Byte
0TB, 298GB, 753MB, 150KB, 679Byte
0TB, 298GB, 896MB, 332KB, 91Byte
0TB, 299GB, 14MB, 282KB, 154Byte
0TB, 299GB, 157MB, 558KB, 82Byte
0TB, 299GB, 300MB, 571KB, 535Byte
0TB, 299GB, 442MB, 96KB, 613Byte
0TB, 299GB, 584MB, 1021KB, 791Byte
0TB, 299GB, 723MB, 664KB, 195Byte