1、c语言计时器
2、c语言定时器
1. clock()函数
需要引用头文件 “time.h”
注:clock函数返回从开始这个程序到调用的 clock() 函数之间的CPU时钟计时单元(clock tick)数。返回值类型是 clock_t。其中 CLOCKS_PER_SEC 是一个常数,表示一秒钟有多少个时钟数。
#include<time.h>
int main(){
clock_t start, end;
start = clock();
/*...
需要计时的代码
...*/
end = clock();
printf("time=%f\n", (double)(end - start) / CLOCKS_PER_SEC);
return 0;
}
2. 1time(), difftime() 函数
返回从1970年1月1日00:00:00到现在经过的秒数
注:建议使用 difftime() 来计算程序执行所花时间(更精确,单位:s
#include<time.h>
int main(){
time_t start,end;
start = time(NULL);
/*...
需要计时的代码
...*/
end = time(NULL);
printf("time = %ds\n", difftime(end, start));
return 0;
}
2.2 每隔10s打印
#include <stdio.h>
#include <time.h>
int main(int argc,char **argv)
{
time_t timep;
time(&timep); //返回从1970-01-01 00:00:00到现在的秒数
int last_time=timep; //获取一开始的时间
printf("开始时间是:%ds\n",last_time);
while(1) //死循环,直到t-last_time==10,进程才会结束
{
time_t t;
time(&t); //当前时间一直改变
if(t-last_time==10) //当t-last_time==10,即时间相较于一开始过了10s
{
printf("现在时间是:%ds,已过10s,打印信息,结束进程\n",t);
return 0;
}
else
{
continue;
}
}
return 0;
}
3. gettimeoftoday() 函数
函数原型:int gettimeofday(struct timeval *tv, struct timezone *tz)
1.该函数是 Linux 系统专属函数,可以精确到微秒 (us);
2.其中参数tv是保存获取时间的结果类型,参数tz用于保存时区结果 (若不使用可以传入NULL)。
#include<sys/time.h>
int mian(){
struct timeval start,end;
gettimeofday(&start, NULL);
/*...
需要计时的代码
...*/
gettimeofday(&end, NULL);
long timeuse = 1000000*(end.tv_sec - start.tv_sec) + end.tv_usec-start.tv_usec;
printf("time =%f 秒\n", timeuse/1000000)
return 0;
}
2.c语言定时器
#include <stdio.h>
#include <windows.h>
void CALLBACK timer_handler(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) {
printf("Timer expired!\n");
}
int main() {
// 创建窗口,用于接收消息
HWND hwnd = CreateWindow("STATIC", "", 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL);
// 创建定时器,每隔2秒触发一次
UINT_PTR timerId = SetTimer(hwnd, 1, 2000, timer_handler);
// 等待消息循环结束
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// 删除定时器
KillTimer(hwnd, timerId);
return 0;
}