加权轮询算法

    技术2024-11-19  10

    #include<iostream> #include<vector> #include<string> using namespace std; struct Server { int weight; string name; int curWeight; }; Server* smoothWrr(vector<Server*>& servers) { int n = servers.size(); int maxIndex = -1; int totalWeight = 0; for(int i = 0; i < n; i++) { servers[i]->curWeight += servers[i]->weight; if(maxIndex == -1 || servers[i]->curWeight > servers[maxIndex]->curWeight) { maxIndex = i; } totalWeight += servers[i]->weight; } servers[maxIndex]->curWeight -= totalWeight; return servers[maxIndex]; } void initServers(int ws[], string names[], int n, vector<Server*>& servers) { for(int i = 0; i < n; i++) { Server* server = new Server; server->weight = ws[i]; server->name = names[i]; server->curWeight = 0; servers.push_back(server); } } int main() { int weights[] = {1, 2, 4}; string names[] = {"a", "b", "c"}; vector<Server*> servers; initServers(weights, names, sizeof(weights)/sizeof(int), servers); for(int i = 0; i < 7; i++) { Server* server = smoothWrr(servers); cout << "name: " << server->name << "\tweight: " << server->weight << endl; } return 0; }

     

    Processed: 0.406, SQL: 9