实现Linux版本的 cpu 正弦曲线
#include <iostream>
#include <time.h>
#include <math.h>
using namespace std;
typedef long long int int64;
int64 GetTickCount()
{
timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
int64 sec = now.tv_sec;
int64 nsec = now.tv_nsec;
return sec*1000 + nsec/1000000;
}
void cpu_sin()
{
const int SAMPLE_COUNT = 100;
const int SAMPLE_TIME = 100;
const double PI = 3.1415926;
const double DELTA = 2*PI/SAMPLE_COUNT;
int sample_value[SAMPLE_COUNT];
for(int i = 0; i<SAMPLE_COUNT; ++i)
{
sample_value[i] = SAMPLE_TIME/2 * (sin(DELTA * double(i)) + 1) + 1;
}
int j = 0;
while(true)
{
int64 start= GetTickCount();
while(GetTickCount() - start < sample_value[j])
;
usleep((SAMPLE_TIME - sample_value[j])*1000);
j = (++j)%SAMPLE_COUNT;
}
}
int main() {
cpu_sin();
return 0;
}
实现到方法和windows版本类似。都是采样,在一个非常小到时间间隔里控制cpu到使用时间,让cpu忙碌到时间成正弦曲线。
这里需要用到linux版本到获取时间到方法。在windwos版本中,GetTickCount()函数非常好用,能获得毫秒时间。而且本问题正需要毫秒级别的控制。
因此打算在Linux中山寨一个毫秒级别的GetTickCount。由于Second * 1000 很有可能超出 long int 的范围,因此定义了long long int,它是64位的
注意各种单位:
timespce 中的nsec是纳秒级别的,sec是秒级别到
sleep()中到参数是秒,不同与windows的ms,usleep的参数是微妙级别