Skip to content

Instantly share code, notes, and snippets.

@HyodaKazuaki
Created August 19, 2017 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HyodaKazuaki/d90abb66f40323e92e29f13872d5a6e8 to your computer and use it in GitHub Desktop.
Save HyodaKazuaki/d90abb66f40323e92e29f13872d5a6e8 to your computer and use it in GitHub Desktop.
C言語による演算速度の計測
#include <stdio.h>
#include <time.h>
// ループ回数設定、今回は1億回
#define LOOP 100000000
int main(void)
{
// 変数宣言
int i, num;
clock_t start, past;
printf("各演算での計算時間について\n");
printf("ループ回数 : %d回\n", LOOP);
printf("開始\n");
// 演算開始 //
// 加算
for(i = 0, past = 0, num = 0; i < LOOP; i++){
start = clock();
num = num + i; // numは0~99999999まで代入されます
past += clock() - start;
}
printf("加算 : %f[s]\n", (double)(past) / CLOCKS_PER_SEC);
// 減算
for(i = 0, past = 0, num = 0; i < LOOP; i++){
start = clock();
num = num - i; // numは0~-99999999まで代入されます
past += clock() - start;
}
printf("減算 : %f[s]\n", (double)(past) / CLOCKS_PER_SEC);
// 乗算
for(i = 0, past = 0; i < LOOP; i++){
num = 1; // オーバーフローを回避するために毎回1に戻します
start = clock();
num = num * i; // numは0~99999999まで代入されます
past += clock() - start;
}
printf("乗算 : %f[s]\n", (double)(past) / CLOCKS_PER_SEC);
// 除算
for(i = 1, past = 0; i <= LOOP; i++){ // ゼロ除算回避の為、制御変数iは1からスタートしています
num = LOOP;
start = clock();
num = num / i; // numは100000000~1まで代入されます
past += clock() - start;
}
printf("除算 : %f[s]\n", (double)(past) / CLOCKS_PER_SEC);
// 演算終了 //
printf("終了\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment