Linux下一段获取cpu主频的程序处理正确吗?

源程序是这样的:

#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <stdlib.h>

#include <string.h>
#include <glob.h>
#include <sys/swap.h>
#include <sys/sysinfo.h>
#include <stdint.h>

static inline uint64_t get_cycle_count()
{
	unsigned int lo, hi;
	__asm__ __volatile__("rdtsc" : "=a" (lo), "=d" (hi));
	return ((uint64_t)hi << 32) | lo;
}

int main()
{
	uint64_t old_cycle, new_cycle;
	int i = 0;
	int delayms = 700;

	old_cycle = get_cycle_count();
	usleep(delayms * 1000);
	new_cycle = get_cycle_count();

	printf("%d\n", (new_cycle - old_cycle) / (delayms * 1000));

	return 0;
}

关键点是usleep的延时,这里在单核cpu上是没有问题的,但对于多核心可能会出现线程前后运行在不同的cpu上的问题,如何解决呢?其实也没有好的解决办法!稳妥的方法当然是直接proc了:

除此之外就只能上驱动了! 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值