我想通過將排序函數(bubblesort)的執行時間放入另一個可以計算已用時間的函數來計算它的執行時間。但它一直顯示我的時間:0,因爲我運行它...在C++中計算函數的執行時間
#include <ctime>
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define A_SIZE 100000
void executeTime(int func);
int bubble(int A[], int l, int r);
int main()
{
int A[A_SIZE], i;
int l = 0, r = A_SIZE - 1;
srand((unsigned int)time(0));
for (int i = 0; i < A_SIZE; i++)
{
A[i] = rand();
}
executeTime(bubble(A, l, r));
}
void executeTime(int func) {
int start_s = clock();
func;
int stop_s = clock();
cout << "time: " << (stop_s - start_s)/double(CLOCKS_PER_SEC) * 1000 << endl;
}
int bubble(int A[], int l, int r)
{
int i, j, min;
for (i = l; l < r - 1; l++)
{
min = A[i];
for (j = l + 1; j < r; j++)
{
if (A[j] < min)
{
min = A[j];
A[j] = A[i];
A[i] = min;
}
}
}
return 0;
}
但是,如果我寫的,而不是創建其計算時間和排序陣列離散函數在主塊中的所有代碼,它可以作爲我打算就好了。 這裏有什麼問題?爲什麼我在屏幕上獲得'time:0'?
花幾個星期閱讀一本好的C++編程書,然後看看一些[C++參考](http://en.cppreference.com/w/cpp)。你有一個很大的誤解,**我們不能在這裏教你C++。** –
'func;'不是一個函數調用(而且'int func'不會傳遞一個函數作爲參數,它只是一個值 - 在這種情況下,'bubble'的結果) – UnholySheep
'executeTime(bubble(A,l,r));'相當於'int temp = bubble(A,l,r); executeTime(temp);'因此不是你認爲的 –