一、介绍
通过C++和C#的几个类库实现计时器,通过计时器来统计程序允许的时间.实际使用中毫秒计时器就足够了。
二、毫秒计时器
#include<ctime>
class Timer_milisecode{//
public:
Timer_milisecode(){
tbegin=clock();
tend=clock();
}
void begin(){
tbegin=clock();
}
void end(){
tend=clock();
}
double spent(){
return double(tend-tbegin)/CLOCKS_PER_SEC*1000;
}
double getCurrentTime(){
return double(clock());
}
private:
// const int clock_per_second=CLOCKS_PER_SEC;
clock_t tbegin,tend;
};
头文件为 #include<ctime> ,详解
ctime下有一个clock_t类型(long),和一个对应的函数clock(),其返回值为clock_t类型,同时有一个常量 CLOCKS_PER_SEC,这个常量表示每秒的打点数,理论上来说,clock()应该是每毫秒打一次点。在计算时间间隔是,两个clock_t数相减,然后修正一下就是毫秒数
三、微秒计时器
#include<Windows.h>
class Timer_microseconds{
public:
Timer_microseconds(){
QueryPerformanceFrequency(&tc);
}
void begin(){
QueryPerformanceCounter(&t1);
}
void end(){
QueryPerformanceCounter(&t2);
}
double spent(){
return (double(t2.QuadPart-t1.QuadPart)*1000000.0)/tc.QuadPart;
}
private:
LARGE_INTEGER t1,t2,tc;
};
头文件为 #include<windows.h>
与上面类似。首先是定义三个LARGE_INTEGER 变量。存在两个函数 QueryPerformanceFrequency(),查询每秒的贫困频率,QueryPerformanceCounter(),计数器。然后这里的话,理论上来说,tc.QuadPart的值为10_000_000每秒,即每微秒会计数10个。这个是比较精确的。
四、微秒计数器
#include<chrono>
class Timer_chrono{
public:
Timer_chrono(){
}
void begin(){
start=std::chrono::high_resolution_clock::now();
}
void end(){
spentTime=std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now()-start).count();
}
double spent(){
return (double)spentTime;
}
private:
std::chrono::time_point<std::chrono::high_resolution_clock> start;
long long spentTime;
};
需要用到头文件<chrono>,就是上面这样吧。
五、C# 计时器
class Timer
{
private DateTime dt;
private TimeSpan tSpen;
public Timer()
{
dt= DateTime.Now;
}
public void begin()
{
dt= DateTime.Now;
}
public void end()
{
tSpen=DateTime.Now-dt;
}
public double spent()
{
return tSpen.TotalMilliseconds;
}
}
实际上来说,C#应该并不需要什么计时器,DateTime和TimeSpan两个类就可以了。最高精读是毫秒。
六、C++获取当前时间
time_t tm0;
time(&tm0);
std::cout<<tm0<<endl;
cout<<ctime(&tm0)<<endl;
输出结果为 Mon Mar 20 23:29:15 2023。ctime就是将秒数进行格式化字符串
tm ttm= *localtime(&tm0);
cout<<ttm.tm_year<<"\t"<<ttm.tm_mon<<"\t"<<ttm.tm_mday<<endl;
struct tm,输出自1900年开始的年份和时间。