Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cmath>
- #include <chrono>
- #include <iostream>
- const int64_t MAX = 10000000;
- int64_t while_count(int64_t n) {
- int64_t count = 0;
- while (n != 0) {
- n /= 10;
- count++;
- }
- return count;
- }
- int64_t log10_count(int64_t n) {
- return (int64_t) (log10(n) + 1);
- }
- int64_t string_count(int64_t n) {
- return std::to_string(n).size();
- }
- template<typename Function>
- long time(Function func) {
- auto start = std::chrono::high_resolution_clock::now();
- for (int64_t i = 0; i < MAX; i++) {
- func(i);
- }
- auto finish = std::chrono::high_resolution_clock::now();
- auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
- std::cout << "Average " << duration / MAX << "ns" << std::endl;
- std::cout << "Total " << duration << "ns" << std::endl;
- return duration;
- }
- void print_stats(const std::string &type, long time, long while_time) {
- auto diff = while_time - time;
- auto perc = static_cast<float>((float) diff / (float) while_time) * 100;
- std::cout << std::endl << type << " is " << diff / MAX << "ns faster per operation than while" << std::endl;
- std::cout << type << " is " << perc << "% faster than while-loop" << std::endl;
- }
- int main() {
- std::cout << "While-loop" << std::endl;
- auto while_time = time(while_count);
- std::cout << std::endl << "log10" << std::endl;
- auto log_time = time(log10_count);
- std::cout << std::endl << "string" << std::endl;
- auto string_time = time(string_count);
- print_stats("log", log_time, while_time);
- print_stats("string", string_time, while_time);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement