|
D Paste by downs
Description: geobench.d with validation
|
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 77 78 79 80 81 82 83 84 85 | module geobench; import tools.time, tools.log, tools.base, std.string, std.socket; uint toNumeric(string ip) { uint res; ubyte cur; foreach (ch; ip) { if (ch == '.') { res = (res << 8) + cur; cur = 0; } else cur = cur * 10 + (ch - '0'); } res = (res << 8) + cur; return res; } class GeoIP { import std.file; static { struct entry { uint start; string country; } entry[] list; string lookup(uint what) { auto range = list; while (range.length > 1) { auto center = range[$/2]; if (center.start == what) return center.country; if (center.start < what) range = range[$/2 .. $]; else range = range[0 .. $/2]; } return range[0].country; } } static this() { string[string] countries; // lookup is by string equality "GeoIPCountryWhois.csv".read().castLike("").split("\n") /map/ (string line) { line = line.strip(); if (!line.length) return; auto parts = line[1 .. $-1].split("\",\""); // remove ""s auto ip = parts[0]; entry e; // why parse IPs? Let the system do it for us. e.start = (new InternetAddress(ip, 0)).addr(); e.country = parts[$-1]; if (auto p = e.country in countries) e.country = *p; else countries[e.country] = e.country; list ~= e; // yes they're ordered }; logln(list.length, " ranges added, using ", countries.values.length, " countries. "); logln("Performing lookup tests ... "); auto start = sec(); long total, correct; foreach (line; "GeoIPCountryWhois.csv".read().castLike("").split("\n")) { line = line.strip(); if (!line.length) continue; auto parts = line[1 .. $-1].split("\",\""); // remove ""s auto ip = parts[0]; total ++; if (parts[5] == lookup(ip.toNumeric())) correct ++; } auto stop = sec(); logln(correct, " / ", total, " validated in ", stop-start, "s"); if (correct != total) throw new Exception("Please fix this first"); } } import tools.mersenne; void main() { long count; auto last = sec(); while (true) { string country; for (int i = 0; i < 16; ++i) { auto rand_ip = rand(); country = GeoIP.lookup(rand_ip); count ++; } auto s = sec(); if (s > last + 1) { last = s; logln(count, " lookups per second, last country was ", country); count = 0; } } } |
(some replies deleted)