新手用GetTickCount出错,请指教
目的是测出线性检索、二分检索的时间耗费情况,数组初始化用rand,请高手指教:
- C/C++ code
#include<cstdio>#include<cstring>#include<cstdlib>#include<cmath>#include<string>#include<iostream>#include<iomanip>#include<windows.h>#include<ctime>#define N 8000000using namespace std;int a[N+1];int cmp(const void *a,const void *b){ return *(int *)a-*(int *)b;}int ran_get_ele(){ int i=0,key=rand(); for(;i<N;i++){ //srand(time(0)); a[i]=rand(); } return key;}int linearSearch(int key){ DWORD take=GetTickCount(); for(int i=0;i<N;i++) if(a[i]==key){ cout<<"time consumed using linearySearch is "<<GetTickCount()-take<<endl; return i; } cout<<"time consumed using linearySearch is "<<GetTickCount()-take<<endl; return -1;}int binarySearch(int key){ DWORD take=GetTickCount(); int low=0,high=N-1,mid; while(low<=high){ mid=(low+high)/2; if(a[mid]==key){ cout<<"time consumed using binarySearch is "<<GetTickCount()-take<<endl; return mid; } key<a[mid] ? high=mid-1 : low=mid+1; } cout<<"time consumed using binarySearch is "<<GetTickCount()-take<<endl; return -1;}int main(){ int key,tag; key=ran_get_ele();//用rand函数获得数组a和key的值 tag=linearSearch(key); if(tag<0) cout<<"no such element!"<<endl; else cout<<tag<<endl;//若找到输出下标 qsort(a,N,sizeof(a[0]),cmp); tag=binarySearch(key); if(tag<0) cout<<"no such element!"<<endl; else cout<<tag<<endl;//若找到输出下标 return 0;}搞了很久,没弄明白
[解决办法]
GetTickCount返回(retrieve)从操作系统启动到现在所经过(elapsed)的毫秒数,它的返回值是DWORD。
就是个计时的
[解决办法]
For Release configurations, this function returns the number of milliseconds since the device booted, excluding any time that the system was suspended. GetTickCount starts at 0 on boot and then counts up from there.
For Debug configurations, 180 seconds is subtracted from the the number of milliseconds since the device booted. This allows code that uses GetTickCount to be easily tested for correct overflow handling.
Return Values
The number of milliseconds indicates success.
Remarks
The resolution of the system timer is based on the OEM's setting. Check with the OEM for details.
The elapsed time is stored as a DWORD value. Therefore, the time will wrap around to zero if the system is run continuously for 49.7 days.
For Debug configurations, 180 seconds is subtracted to check for overflow conditions in code that relies on GetTickCount. If this code started within 3 minutes of the device booting, it will experience an overflow condition if it runs for a certain amount of time.
Note You should not use GetTickCount for drift sensitive applications.
When using GetTickCount, subtraction is safe but comparisons such as if (GetTickCount() > MyTickCount) are not. You can use the GetTickCount function to time the duration of an activity as shown in the example below, but using GetTickCount for any other operation will cause issues.
[解决办法]