#include <ctime>
#include <string>
#include <iostream>
std::string get_greet(const std::string& who) {
return "Hello " + who;
}
void print_localtime() {
std::time_t result = std::time(nullptr);
std::cout << result << std::endl;
std::cout << std::localtime(&result) << std::endl;
std::cout << std::asctime(std::localtime(&result));
}
int main(int argc, char** argv) {
std::string who = "world";
if (argc > 1) {
who = argv[1];
}
std::cout << get_greet(who) << std::endl;
print_localtime();
return 0;
}
Hello world
1569459184
0x7fea17500180
Thu Sep 26 08:53:04 2019
#include <iostream>
#include <sys/time.h>
#include <unistd.h>
#include <cmath>
using namespace std;
class Timer {
public:
Timer() { Reset(); }
explicit Timer(bool set_timer) { if (set_timer) Reset(); }
void Reset() { gettimeofday(&this->time_start_, &time_zone_); }
double Elapsed() const {
struct timeval time_end;
struct timezone time_zone;
gettimeofday(&time_end, &time_zone);
double t1, t2;
t1 = static_cast<double>(time_start_.tv_sec) +
static_cast<double>(time_start_.tv_usec)/(1000*1000);
t2 = static_cast<double>(time_end.tv_sec) +
static_cast<double>(time_end.tv_usec)/(1000*1000);
return t2-t1;
}
private:
struct timeval time_start_;
struct timezone time_zone_;
};
void Sleep(float seconds){
usleep(static_cast<int>(seconds * 1000000.0));
}
void TimerTest(){
float time_secs = 0.025 * (rand() % 10);
std::cout << "target is " << time_secs << "\n";
Timer timer;
Sleep(time_secs);
float f = timer.Elapsed();
std::cout << "time is " << f << " " << fabs(time_secs - f) << std::endl;
if (fabs(time_secs - f) > 0.05)
cout << "Timer fail: waited " << f << " seconds instead of "
<< time_secs << " secs.";
}
int main() {
for (int i = 0; i < 5; i++)
TimerTest();
return 0;
}
target is 0.075
time is 0.0751109 0.000110909
target is 0.15
time is 0.15011 0.00011
target is 0.175
time is 0.175105 0.000105098
target is 0.125
time is 0.125109 0.000108957
target is 0.075
time is 0.075103 0.000103042