一段代码,演示高速缓存命中的效率提升

#include <Windows.h>

inline void demo_proc(int index)
{
	for (int i = 1; i <= 10000000; i++)
	{
		demo_acc[index] += (float)(((i % 2) * -1) * 2 + 1);
	}
}

DWORD WINAPI DispProc0(LPVOID lpVoid)
{
	int *flag = (int *)lpVoid;
	while (*flag < 0)
	{
		_mm_pause();
	}
	int index = *flag;

	DWORD tickCount = GetTickCount();
	for (int i = 0; i < 13; i++)
	{
		demo_proc(index + i);
	}
	printf("thread %d cost %d ms looping from %d to %d.\r\n", index / 13, GetTickCount() - tickCount, index, index + 13);
	return 0;
}

DWORD WINAPI DispProc1(LPVOID lpVoid)
{
	int *flag = (int *)lpVoid;
	while (*flag < 0)
	{
		_mm_pause();
	}
	int index = *flag;

	DWORD tickCount = GetTickCount();
	for (int i = 0; i < 16; i++)
	{
		demo_proc(index + i);
	}
	printf("thread %d cost %d ms looping from %d to %d.\r\n", index / 16, GetTickCount() - tickCount, index, index + 16);
	return 0;
}

DWORD WINAPI DispProc2(LPVOID lpVoid)
{
	int *flag = (int *)lpVoid;
	while (*flag < 0)
	{
		_mm_pause();
	}
	int index = *flag;

	DWORD tickCount = GetTickCount();
	for (int i = index; i < (13 * 4); i++)
	{
		demo_proc(i);
	}
	printf("thread %d cost %d ms looping from %d to %d.\r\n", index / 16, GetTickCount() - tickCount, index, 13 * 4);
	return 0;
}

int main(int argc, char **argv)
{
	volatile int index[4] = { -1 };	// ###
	HANDLE threads[4];
	DWORD tickCount = GetTickCount();
	for (int i = 0; i < (13 * 4); i++)
	{
		demo_proc(i);
	}
	printf("single thread cost %d ms.\r\n", GetTickCount() - tickCount);

	for (int i = 0; i < 4; i++)
	{
		index[i] = -1;
		threads[i] = CreateThread(NULL, 0, DispProc0, (LPVOID)(index + i), 0, NULL);
	}

	tickCount = GetTickCount();
	for (int i = 0; i < 4; i++)
	{
		index[i] = i * 13;
	}
	WaitForMultipleObjects(4, threads, TRUE, INFINITE);
	printf("simple multi-thread cost %d ms.\r\n", GetTickCount() - tickCount);
	for (int i = 0; i < 4; i++)
	{
		CloseHandle(threads[i]);
	}


	for (int i = 0; i < 4; i++)
	{
		index[i] = -1;
		threads[i] = CreateThread(NULL, 0, i == 3 ? DispProc2 : DispProc1, (LPVOID)(index + i), 0, NULL);
	}

	tickCount = GetTickCount();
	for (int i = 0; i < 4; i++)
	{
		index[i] = i * 16;
	}
	WaitForMultipleObjects(4, threads, TRUE, INFINITE);
	printf("aligned multi-thread cost %d ms.\r\n", GetTickCount() - tickCount);
	for (int i = 0; i < 4; i++)
	{
		CloseHandle(threads[i]);
	}

	return 0;
}

运行效果:

下一篇将演示使用缓存进行高性能的线程同步。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值