Comparing performance of a task queued to an existing thread vs. new thread for each task.
修訂 | 6364b03e62e62258f90af6af39fe4497c2927054 (tree) |
---|---|
時間 | 2017-03-24 02:23:40 |
作者 | Eric Hopper <hopper@omni...> |
Commiter | Eric Hopper |
Just threads vs. raw function call for now.
@@ -0,0 +1,3 @@ | ||
1 | +extern void do_something() | |
2 | +{ | |
3 | +} |
@@ -0,0 +1,59 @@ | ||
1 | +#include <chrono> | |
2 | +#include <thread> | |
3 | +#include <future> | |
4 | +#include <iostream> | |
5 | + | |
6 | +extern void do_something(); | |
7 | + | |
8 | +typedef long long unsigned int calls_p_sec_t; | |
9 | +typedef ::std::function<void ()> the_call_t; | |
10 | + | |
11 | +template <typename T> | |
12 | +calls_p_sec_t calls_per_second(const T &thecall, unsigned int interval) | |
13 | +{ | |
14 | + auto now = []() -> auto { | |
15 | + return ::std::chrono::high_resolution_clock::now(); | |
16 | + }; | |
17 | + typedef ::std::chrono::duration<long double> timediff_t; | |
18 | + unsigned long long count = 0; | |
19 | + const auto start = now(); | |
20 | + | |
21 | + long double curtime_as_ldbl = (timediff_t(now() - start)).count(); | |
22 | + while (curtime_as_ldbl < interval) { | |
23 | + thecall(); | |
24 | + ++count; | |
25 | + curtime_as_ldbl = (timediff_t(now() - start)).count(); | |
26 | + } | |
27 | + return count / interval; | |
28 | +} | |
29 | + | |
30 | +int main() | |
31 | +{ | |
32 | + using ::std::cout; | |
33 | + using ::std::async; | |
34 | + using ::std::thread; | |
35 | + using ::std::launch; | |
36 | + cout << " Do nothing calls per second: " | |
37 | + << calls_per_second([]() { }, 5) << '\n'; | |
38 | + cout << " Empty calls per second: " | |
39 | + << calls_per_second([]() { do_something(); }, 5) << '\n'; | |
40 | + cout << " New thread calls per second: " | |
41 | + << calls_per_second( | |
42 | + []() { | |
43 | + thread t{ do_something }; | |
44 | + t.join(); | |
45 | + }, | |
46 | + 5 | |
47 | + ) | |
48 | + << '\n'; | |
49 | + cout << "Async launch calls per second: " | |
50 | + << calls_per_second( | |
51 | + []() { | |
52 | + auto fut = async(launch::async | launch::deferred, do_something); | |
53 | + fut.wait(); | |
54 | + }, | |
55 | + 5 | |
56 | + ) | |
57 | + << '\n'; | |
58 | + return 0; | |
59 | +} |