我正在对排序速度进行一些测量,并正在测量对 100 万个浮点值进行排序所花费的时间,所有浮点值都在 [0,1] 之间,使用 <algorithm>.
中的标准 std::sort|在我的硬件上,带有 6 GB Ram 的英特尔酷睿 i5,下面的代码显示它大约需要 1164.188 毫秒。但是,我怀疑这个的正确性,想问一下这个测量是否正确。请看下面的代码来了解我是如何得到 1164.188ms
#include<algorithm>
#include<iostream>
#include<windows.h>
using namespace std;
void main(){
const int N = 1000000;
FILE *f;
f = fopen("invertedList.txt","r");
if( f == NULL){
printf("File not found\n");
system("pause");
exit(1);
}
int count = 0 ;
//read input from a file
float* a = (float*)malloc(N * sizeof(float));
for( int i =0 ; i < N ; i++){
fscanf(f, "%f,", &a[count]);
count++;
}
fclose(f);
//start the clock
__int64 ctr1 = 0 , ctr2 = 0 , freq = 0 ;
QueryPerformanceFrequency((LARGE_INTEGER *) &freq);
QueryPerformanceCounter((LARGE_INTEGER *) &ctr1);
sort(a,a+N);
QueryPerformanceCounter((LARGE_INTEGER *)&ctr2);//stop clock
double ans = ((ctr2 - ctr1) * 1.0 / freq);
printf("The time elapsed in milliseconds is %f\n",(ans*1000));
FILE *tow;
tow = fopen("writesort.txt","w");
for(int i =0 ; i< N;i++){
fprintf(tow,"%f,",a[i]);
}
free(a);
fclose(tow);
getchar();
}
最佳答案
我会在 fscanf(f, "%f,", &a[count]);
的返回值中添加一个检查,以确保它读取并转换了一个值。
时序逻辑似乎是合理的。请注意,它正在测量耗时。至于准确测量算法,只有在机器负载较轻或负载较小的情况下才是正确的。多次运行可以指示时间有效性:如果接近,则它们可能是准确的。如果变化很大 (> 25%),则其他系统操作会干扰计算。
关于c++ - 算法库排序100万个0到1 float 的测时耗时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8630965/