ArnovLiere

Untitled

Jan 14th, 2021 (edited)
513
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <cmath>
  2. #include <chrono>
  3. #include <iostream>
  4.  
  5. const int64_t MAX = 10000000;
  6.  
  7. int64_t while_count(int64_t n) {
  8.     int64_t count = 0;
  9.     while (n != 0) {
  10.         n /= 10;
  11.         count++;
  12.     }
  13.     return count;
  14. }
  15.  
  16. int64_t log10_count(int64_t n) {
  17.     return (int64_t) (log10(n) + 1);
  18. }
  19.  
  20. int64_t string_count(int64_t n) {
  21.     return std::to_string(n).size();
  22. }
  23.  
  24. template<typename Function>
  25. long time(Function func) {
  26.     auto start = std::chrono::high_resolution_clock::now();
  27.     for (int64_t i = 0; i < MAX; i++) {
  28.         func(i);
  29.     }
  30.     auto finish = std::chrono::high_resolution_clock::now();
  31.     auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
  32.     std::cout << "Average " << duration / MAX << "ns" << std::endl;
  33.     std::cout << "Total   " << duration << "ns" << std::endl;
  34.     return duration;
  35. }
  36.  
  37. void print_stats(const std::string &type, long time, long while_time) {
  38.     auto diff = while_time - time;
  39.     auto perc = static_cast<float>((float) diff / (float) while_time) * 100;
  40.  
  41.     std::cout << std::endl << type << " is " << diff / MAX << "ns faster per operation than while" << std::endl;
  42.     std::cout << type << " is " << perc << "% faster than while-loop" << std::endl;
  43. }
  44.  
  45. int main() {
  46.     std::cout << "While-loop" << std::endl;
  47.     auto while_time = time(while_count);
  48.  
  49.     std::cout << std::endl << "log10" << std::endl;
  50.     auto log_time = time(log10_count);
  51.  
  52.     std::cout << std::endl << "string" << std::endl;
  53.     auto string_time = time(string_count);
  54.  
  55.     print_stats("log", log_time, while_time);
  56.     print_stats("string", string_time, while_time);
  57.  
  58.     return 0;
  59. }
  60.  
RAW Paste Data