changeset 16:d6798d2acfb3

Improve timeit_f for void functions
author Lewin Bormann <lbo@spheniscida.de>
date Sat, 01 Apr 2023 19:35:47 +0200
parents fc43055d41d8
children f3324364ceda
files lib/exec.h sorting.cc
diffstat 2 files changed, 28 insertions(+), 14 deletions(-) [+]
line wrap: on
line diff
--- a/lib/exec.h	Wed Mar 22 21:56:20 2023 +0100
+++ b/lib/exec.h	Sat Apr 01 19:35:47 2023 +0200
@@ -12,7 +12,26 @@
 
 using std::function, std::string, std::chrono::high_resolution_clock;
 
-template<typename F>
+template<typename Func>
+concept is_void_function = std::is_void_v<std::invoke_result_t<Func>>;
+
+template<typename F> requires is_void_function<F>
+void timeit_f(F f, string name = string()) {
+    auto begin = high_resolution_clock::now();
+
+    f();
+
+    auto after = high_resolution_clock::now();
+
+    auto d = after - begin;
+    decltype(d)::rep count = d.count();
+    decltype(d)::period p;
+
+    fmt::print("(void) {} :: {} s\n", name, static_cast<double>(p.num)/p.den * count); 
+    return;
+}
+
+template<typename F> requires (!is_void_function<F>)
 auto timeit_f(F f, string name = string()) -> decltype(f()) {
     auto begin = high_resolution_clock::now();
 
--- a/sorting.cc	Wed Mar 22 21:56:20 2023 +0100
+++ b/sorting.cc	Sat Apr 01 19:35:47 2023 +0200
@@ -1,5 +1,7 @@
 #include <cassert>
 
+#include "lib/exec.h"
+
 #include <algorithm>
 #include <functional>
 #include <iostream>
@@ -12,10 +14,11 @@
 template<typename T>
 int partition(vector<T>& v, int left, int right) {
     int mid = (left+right)/2;
+    T piv = v[mid];
     while (left <= right) {
-        while (v[left] < v[mid])
+        while (v[left] < piv)
             left++;
-        while (v[right] > v[mid])
+        while (v[right] > piv)
             right--;
         if (left < right) {
             T b = v[left];
@@ -178,17 +181,9 @@
 
 int main(void) {
     vector<string> v{"hello", "olleh", "abc", "bca", "world", "wrlod"};
-    vector<int> vi{1,2,3,4,5,6,7,8,9,10};
+    vector<int> vi{5,5,6,1,3,2,5,8,9};
 
-    // vi:
-    // 10
-    // ->             9                     7
-    // ->        8          5        6           3
-    // ->    1       4    2    x   x   x       x    x
-    make_into_heap(vi, SiftDirection::Up);
-
-    for (const auto& a : vi)
-        std::cout << a << " ";
-    std::cout << "\n";
+    timeit_f([&vi]() -> void { quicksort(vi); }, "quicksort");
+    fmt::print("{}\n", vi);
     return 0;
 }