Skip to content

Instantly share code, notes, and snippets.

@zed
Created August 8, 2012 17:01
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 zed/3296666 to your computer and use it in GitHub Desktop.
Save zed/3296666 to your computer and use it in GitHub Desktop.
demonstrate that unlike clock() the chrono::steady_clock doesn't ignore sleep(), children time :c++11:chrono:clock:
// $ sudo apt-get install libboost-{system,chrono}1.48-dev
// $ g++ *.cpp -lboost_{system,chrono} && time ./a.out
#include <boost/chrono.hpp> // <chrono> in C++11
#include <iostream>
#include <string>
#include <stdint.h> // uintmax_t
#include <stdlib.h> // system()
#include <unistd.h> // sleep()
namespace {
namespace chrono = boost::chrono;
typedef chrono::steady_clock Clock; //
class Timeit {
std::string msg;
Clock::time_point start;
public:
explicit Timeit(std::string msg_) : msg(msg_), start(Clock::now()) {}
~Timeit() {
Clock::duration dur = Clock::now() - start;
std::cout << "'" << msg << "' took us " << dur << std::endl;
// to get float number of seconds:
// << std::setprecision(3)
// << chrono::duration_cast<chrono::duration<double> >(dur).count()
// to get integer number of milliseconds:
// << chrono::duration_cast<chrono::milliseconds >(dur).count()
}
};
}
int main(int argc, char* argv[]) {
{ Timeit _("sleep");
sleep(1);
}
{ Timeit _("system sleep");
system("sleep 1");
}
{ Timeit _("loop");
int n = (argc == 2) ? atoi(argv[argc-1]) : 500000000;
uintmax_t s = 0;
for (int i = 0; i < n; ++i)
s += i;
if (s != (uintmax_t)(n-1)*(n/2)) return 1;
}
}
// $ gcc -std=c99 *.c && time ./a.out
#include <stdint.h> // uintmax_t
#include <stdio.h>
#include <stdlib.h> // system()
#include <time.h>
#include <unistd.h> // sleep()
static double double_clock() {
return clock() / (double) CLOCKS_PER_SEC;
}
int main(int argc, char* argv[]) {
double start = double_clock();
sleep(1);
printf("after sleep %.2g\n", double_clock() - start);
start = double_clock();
system("sleep 1");
printf("after sleep %.2g\n", double_clock() - start);
start = double_clock();
int n = (argc == 2) ? atoi(argv[argc-1]) : 500000000;
uintmax_t s = 0;
for (int i = 0; i < n; ++i)
s += i;
if (s != (uintmax_t)(n-1)*(n/2)) return 1;
printf("after loop %.2g\n", double_clock() - start);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment