diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9932039 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.idea +cmake* +CMakeLists.txt +main diff --git a/FunctionTimer.h b/FunctionTimer.h new file mode 100644 index 0000000..3f3f192 --- /dev/null +++ b/FunctionTimer.h @@ -0,0 +1,61 @@ +#ifndef FUNCTIONTIMER_H +#define FUNCTIONTIMER_H + +#include +#include +#include + +class FunctionStats { +private: + int64_t longest_time = 0; // the longest function running time + int64_t shortest_time = std::numeric_limits::max(); // the shortest function running time + int64_t total_time = 0; + int64_t count = 0; // number of times the function being called + std::string time_unit; + +public: + FunctionStats(std::string time_unit_): time_unit(time_unit_){} + + void update_time(int running_time) { + ++count; + total_time += running_time; + + if (running_time > longest_time) longest_time = running_time; + if (running_time < shortest_time) shortest_time = running_time; + } + + void print_stats() const{ + std::cout << "=========================================================" << std::endl; + std::cout << "this function has run " << count << " times" << std::endl; + std::cout << "average function running time: " << (int64_t)(total_time / count) << time_unit << std::endl; + std::cout << "longest function running time: " << longest_time << time_unit << std::endl; + std::cout << "shortest function running time: " << shortest_time << time_unit << std::endl; + std::cout << "=========================================================" << std::endl; + } +}; + +// time the function for running once, default unit is millisecond +class FunctionTimer { +private: + timeval start; + timeval end; + +public: + void start_timer () { + gettimeofday(&start, NULL); + } + + void calculate_time() { + gettimeofday(&end, NULL); + } + + int64_t get_elapsed_time_in_milliseconds() const { + return (end.tv_usec - start.tv_usec) / 1000; + } + + int64_t get_elapsed_time_in_microseconds() const { + return end.tv_usec - start.tv_usec; + } +}; + +#endif diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..5f67694 --- /dev/null +++ b/Makefile @@ -0,0 +1,7 @@ +CC=g++ + +main: main.cpp + ${CC} -o $@ $^ + +clean: + rm -f main \ No newline at end of file diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..738af26 --- /dev/null +++ b/main.cpp @@ -0,0 +1,28 @@ +#include +#include "FunctionTimer.h" + +using namespace std; + +FunctionStats STAT("u"); + +void func() { + int x = 0; + for (int i = 0; i < 1000000; ++i) { + x += 1; + } +} + +int main() { + FunctionTimer timer(1000000); + cout << "Program starts" << endl; + + for (int i = 0; i < 10; ++i) { + timer.start_timer(); + func(); + timer.calculate_time(); + STAT.update_time(timer.get_elapsed_time()); + } + STAT.print_stats(); + + return 0; +}