两个C++毫秒级定时器

Win32控制台测试程序如下, 其中完整的程序代码下载是: http://download.csdn.net/detail/hemmingway/4600235


// Test_Time.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "Timer.h"
#include "TimeCounter.h"

#define N 10000

#define TEST_PRO  \
		for(int i = 0; i < N; ++i) \
		{ \
		  for (int j= 0; j < N; ++j) \
		  {} \
		} \
		printf("loop ok...\n\n") \

#define TIME_START CTimeCounter* pT = new CTimeCounter()
#define TIME_END   ShowTime(pT->GetExecutionTime())


//
// Show execution time (ms)
void ShowTime(int64_t nTime)
{
	printf("Total time: %I64d millisecond\n\n",nTime);		//在g++中对应的是<stdint.h> int64_t, 应该用%lld输出
}

int _tmain(int argc, _TCHAR* argv[])
{
	CTimer time;
	printf("1. CTimer\n\n");
	time.start("CTimer");

	TEST_PRO;

	time.plot();

	getchar();

	printf("2. CTimeCounter\n\n");
	TIME_START;

	TEST_PRO;

	TIME_END;

	getchar();
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ 中,你可以通过使用计时器库或者定时器类来实现绑定多个回调的毫秒定时器。以下是一个示例使用 C++11 标准库的 `std::thread` 和 `std::chrono` 来实现的简单定时器: ```cpp #include <iostream> #include <thread> #include <chrono> class Timer { public: Timer(std::chrono::milliseconds interval, std::function<void()> callback) : interval_(interval), callback_(callback), is_running_(false) {} void start() { is_running_ = true; thread_ = std::thread([this]() { while (is_running_) { std::this_thread::sleep_for(interval_); callback_(); } }); } void stop() { is_running_ = false; if (thread_.joinable()) { thread_.join(); } } private: std::chrono::milliseconds interval_; std::function<void()> callback_; std::thread thread_; bool is_running_; }; void callback1() { std::cout << "Callback 1 called!" << std::endl; } void callback2() { std::cout << "Callback 2 called!" << std::endl; } int main() { Timer timer1(std::chrono::milliseconds(1000), callback1); Timer timer2(std::chrono::milliseconds(500), callback2); timer1.start(); timer2.start(); std::this_thread::sleep_for(std::chrono::seconds(5)); timer1.stop(); timer2.stop(); return 0; } ``` 在上面的示例中,我们创建了一个 `Timer` 类来表示定时器,通过传入定时间隔和回调函数来初始化定时器。在 `start()` 方法中,我们使用一个循环来等待指定的时间间隔,然后调用回调函数。在 `main()` 函数中,我们创建了两个定时器实例,分别绑定了两个不同的回调函数,并启动了定时器。通过调整定时器的时间间隔和运行时间,你可以自由控制定时器的行为。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值