重要なお知らせ

「教えて! goo」は2025年9月17日(水)をもちまして、サービスを終了いたします。詳細はこちら>

【GOLF me!】初月無料お試し

ソートについて勉強していて、乱数列の要素数Nの値を変えていきバブルソートの交換回数、比較回数を数えるプログラムを作り、後は処理時間について調べたいのですが、処理時間を出力するのはどうやってやるのですか?教えてください。以下に乱数を生成するrand.cとバブルソートを行うbubblesort.cを記載します。これに処理時間を出力するようにしてもらいたいのですが、どうしたらいいですか?解説とソースファイルをよろしくお願いします。

rand.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 1000

int num[N];

int makeDataFile ( void )
{
int i;
FILE *fp;
char s[100];
int num[N];
srand ( ( unsigned )time ( NULL ) );

fp = fopen ("rand1.txt", "w" );
if ( fp == NULL ) exit(1);
for ( i = 0; i < N; i++ ){
fprintf ( fp, "%d\n", rand()%100 );
}
fclose ( fp );

fp = fopen ( "rand1.txt", "r" );
if ( fp == NULL ) exit(1);
while( fgets ( s, sizeof (s), fp ) ) {
printf ( s );
}
fclose ( fp );

return N;
}

bubblesort.c
#include <stdio.h>
#include <time.h>

extern int makeDataFile ( void );
extern int num[];

void BubbleSort ( int x[] , int n );
void Show ( int x[] , int n );

int comp;
int swap;

void BubbleSort ( int x[] , int n )
{
int i, j, tmp;
for ( i = 0; i < n-1; i++ ) {
for ( j = n-1; j > i; j-- ){
comp++;
if ( x[i] > x[j] ){
swap++;
tmp = x[j];
x[j] = x[i];
x[i]= tmp;

Show ( x , n );
}
}
}
}

void Show ( int x[] , int n )
{
while ( n-- )
printf ( "%d " , *x++ );
printf ( "\n" );
}

int main(void)
{
int i, j, n , tmp;
FILE *fp;
comp = 0;
swap = 0;

n = makeDataFile();

fp = fopen ( "rand1.txt", "r" );
if ( fp == NULL ) return 1;

for ( i = 0; i < n; i++ ){
fscanf ( fp, "%d", &(num[i] ) );
}
fclose ( fp );

printf ( "\nbefore bubblesort\n" );
Show ( num , n );
printf ( "\n" );

printf ( "progress bubblesort\n" );
BubbleSort ( num , n );
printf ( "\n" );

printf ( "after bubblesort\n" );
Show ( num , n );
printf ( "\n" );

printf ( "count of comparisons : %d\n" , comp );
printf ( "count of swap : %d\n" , swap );

return 0;
}

A 回答 (2件)

既に回答が出てますが。


OSやコンパイラ等によっては、別の方法が用意されていることがあります。
例えば、 gettimeofday という関数が用意されていることもあります
http://linuxjm.sourceforge.jp/html/LDP_man-pages …


それと、最近はCPUも早くなっているので、1000個くらいのソートだと、バブルソートと他のソートとで、誤差程度の時間しか違わないかもしれません。
    • good
    • 0

関数呼び出しの直前と直後に関数 clock() を呼び、


それぞれの戻り値の差 / CLOCKS_PER_SEC を求めます。

clock_t start, finish;
double duration:

start = clock();
/* ここに計測する部分 */
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;

参考URL:http://msdn.microsoft.com/ja-jp/library/4e2ess30 …
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!