本文介绍了C ++中的确切睡眠时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在C ++中使用Sleep()时,我尝试测量确切的"睡眠时间.

所以,我使用了这段代码

I try to measure the ''exact'' sleep time when I use Sleep() in C++.

So, I used this code

#include <stdio.h>
#include <intrin.h>
#include <windows.h>
#include <iostream>
using namespace std;

unsigned __int64 testSleepExactTime(int relax);
unsigned __int64 getFreqFrom__rdtsc();

int main()
{
	unsigned int relax = 0;
	unsigned __int64 freq = 0;
	freq = getFreqFrom__rdtsc();
	cout <<"Input Relax time (millisec): ";
	cin >> relax;
	cout <<"relax Time : " << relax * 1000<<" Micro Sec."<<endl;
	cout <<"System frequency : "<<freq<<" Ticks per sec."<<endl;
	for(int i = 0;i<10;i++)
		cout <<"Exact relax time : " << testSleepExactTime(relax)*1000000/freq <<" Micro Sec."<< endl;
	for(int i = 0;i<10;i++)
		cout <<"Exact relax time(Double) : " << ((double)testSleepExactTime(relax))*1000000/freq <<" Micro Sec."<< endl;

	system("pause");
	return 0;
}
unsigned __int64 testSleepExactTime(int relax)
{
	unsigned __int64 start = 0;
	unsigned __int64 stop = 0;
	start = __rdtsc();
	Sleep(relax);
	stop = __rdtsc();
	return stop - start;
}
unsigned __int64 getFreqFrom__rdtsc()
{
	 unsigned __int64 start = 0;
	 unsigned __int64 stop = 0;
	 start = __rdtsc();
     Sleep(1000);
	 stop = __rdtsc();
	return stop-start;
}



当我输入1毫秒时,恢复为10000微秒
当我输入1000毫秒时,恢复为995000微秒

为什么当我使用1毫秒时,结果似乎不正确?

注意:
使用MSVC ++ 2010作为工具
基于Windows7
CPU i3 3.07GHz
PS.我不使用"QueryPerformanceFrequency()",因为它每秒返回约290万滴答.



when I input 1 millisecond, it resuted 10000 Microsecond
when I input 1000 millisecond, it resuted 995000 Microsecond

why when I use 1 millisecond that result seem incorrect?

note:
Using MSVC++2010 as tool
Base on Windows7
CPU i3 3.07GHz
PS. I''m not using ''QueryPerformanceFrequency()'' because it returns ~2.9m ticks per sec.

推荐答案



报价:

系统运行时频率无法更改.

The frequency cannot change while the system is running.

表示它没有改变.跟随cpu芯片时钟速度的起伏.

which implies that it does not follow the ups and downs of the cpu chip clock speed.


这篇关于C ++中的确切睡眠时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:00