Skip to content

Instantly share code, notes, and snippets.

@ialexpovad
Last active June 2, 2023 06:28
Show Gist options
  • Save ialexpovad/f6681d656febdd1068c191cd97b95a2b to your computer and use it in GitHub Desktop.
Save ialexpovad/f6681d656febdd1068c191cd97b95a2b to your computer and use it in GitHub Desktop.
Implementation of the Timer class in the programming language С++.
#pragma once
#include <stdio.h>
#include <time.h>
void StartTimer(void);
double StopTimer(void);
double PrintTimer(void);
#if defined(__WIN32__) || defined(_WIN32)
#include <Windows.h>
DWORD m_start, m_end;
#else
#include <sys/time.h>
struct timeval m_start, m_end;
#endif
void StartTimer(void)
{
#if defined(__WIN32__) || defined(_WIN32)
m_start = GetTickCount();
#else
if (gettimeofday(&m_start, 0)) fprintf(stderr, "cant get time!\n");
#endif
}
double StopTimer(void)
{
#if defined(__WIN32__) || defined(_WIN32)
m_end = GetTickCount();
return m_start - m_end;
#else
if (gettimeofday(&tve, 0)) fprintf(stderr, "cant get time!\n");
return 1000 * (m_end.tv_sec - m_start.tv_sec + (double)(m_end.tv_usec - m_start.tv_usec) / 1000000.0);
#endif
}
double PrintTimer(void)
{
double duration;
#if defined(__WIN32__) || defined(_WIN32)
m_end = GetTickCount();
//t = (double)(m_end - tvs) / 1000.0; // seconds
duration = (double)(m_end - m_start); // ms
printf("%.3f ", duration);
return duration;
#else
if (gettimeofday(&tve, 0)) fprintf(stderr, "cant get time!\n");
duration = 1000 * (tve.tv_sec - tvs.tv_sec + (double)(tve.tv_usec - tvs.tv_usec) / 1000000.0);
printf("%.3f ", duration);
return duration;
#endif
}
#include <iostream>
#include <chrono>
#include <thread>
#include <string>
#include "APTimer.h"
#define Name "Alex Povod"
struct Timer
{
std::chrono::time_point<std::chrono::steady_clock> start, end;
std::chrono::duration<float> duration;
Timer()
{
start = std::chrono::high_resolution_clock::now();
}
~Timer()
{
end = std::chrono::high_resolution_clock::now();
duration = end - start;
float ms = duration.count() * 1000.0f;
std::cout << "Timer took " << ms << "ms" << std::endl;
}
};
void Entity()
{
Timer timer;
auto i = 0;
StartTimer();
do { std::cout << "Hello " << Name << std::endl;
i++;
} while (i < 100);
StopTimer();
PrintTimer();
}
int main()
{
#if 0
using namespace std::literals::chrono_literals;
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(1s);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<float> duration = end - start;
std::cout << duration.count() << "s " << std::endl;
#endif
Entity();
std::cin.get();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment