-
Notifications
You must be signed in to change notification settings - Fork 0
/
balance_writing.cpp
76 lines (76 loc) · 1.73 KB
/
balance_writing.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// yuntang
// file:balace_writing.cpp
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <map>
#include "balance_writing.h"
#define TOTAL_RESOURCE 10000
using std::vector;
using std::map;
namespace load_balance
{
LoadBalance::LoadBalance()
{
srand(time(0));
}
LoadBalance::~LoadBalance()
{
}
void LoadBalance::Init(const vector<int>
&server_resource_used)
{
CalculateWeight(server_resource_used);
}
void LoadBalance::Write(vector<int>
&server_resource_used, int request)
{
printf("Writing.....\n");
for (int i = 0; i < request; ++i) {
WriteOnce(server_resource_used);
}
printf("write over!\n");
}
void LoadBalance::Delete(vector<int> &server_resource_used, int idx)
{
if (server_resource_used[idx] > 0) {
--server_resource_used[idx];
CalculateWeight(server_resource_used);
} else {
printf("this server is null, you can not delete from it!\n");
}
}
void LoadBalance::WriteOnce(vector<int> &server_resource_used)
{
double total = 0;
map<double, int> tmp;
for (auto iter = weight_.begin(); iter != weight_.end(); ++iter) {
total += iter->second;
tmp[total] = iter->first;
}
auto select = tmp.upper_bound(rand_range(0, total));
++server_resource_used[select->second];
CalculateWeight(server_resource_used);
}
double LoadBalance::rand_range(double front, double end)
{
double tmp = rand();
if (tmp > 1) {
tmp = tmp - 1;
}
return tmp/(RAND_MAX)*(end-front)+front;
}
void LoadBalance::CalculateWeight(const vector<int>
&server_resource_used)
{
int i = 0;
weight_.clear();
for (auto iter = server_resource_used.begin();
iter != server_resource_used.end(); ++iter) {
double m = static_cast<double>(TOTAL_RESOURCE - *iter + 0.001);
weight_[i] = m * m;
++i;
}
}
} // namespace load_balance