Skip to content

Instantly share code, notes, and snippets.

@qy3u
Last active July 26, 2022 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qy3u/f9e31fd2bd52705b5b8c8e8b2163a464 to your computer and use it in GitHub Desktop.
Save qy3u/f9e31fd2bd52705b5b8c8e8b2163a464 to your computer and use it in GitHub Desktop.
cpp measure elapsed time
// c++11 is required
#include <chrono>
#include <string>
#include <iostream>
class Instant {
std::string description;
std::chrono::time_point<std::chrono::steady_clock> start;
public:
Instant() {
new (this)Instant("");
}
Instant(std::string desc): description(desc) {
start = std::chrono::steady_clock::now();
}
std::chrono::milliseconds elapsed_ms() {
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds> (now - start);
}
void print_elapsed_ms() {
auto elapsed = elapsed_ms();
std::string sep = description.empty()? "" : ",";
std::cout<< description << sep << "elapsed: " << elapsed.count() << "[ms]" << std::endl;
}
};
int main() {
auto instant = Instant();
instant.print_elapsed_ms();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment