0
如何修改此代碼做序列 程序來計算複雜數字的點積 所需的掛鐘時間 (time_t)。牆上時鐘的計算
#include "stdafx.h"
#include <stdlib.h>
#include<stdio.h>
typedef struct complex{
double real;
double img;
}complex;
complex add(complex a, complex b);
complex multiply(complex *a, complex *b);
int _tmain(int argc, _TCHAR* argv[])
{
int choice, temp1, temp2;
complex a, b, c;
while (1)
{
printf("Press 1 to add two complex numbers.\n");
printf("Press 2 to multiply two complex numbers.\n");
printf("Press 3 to exit.\n");
printf("Enter your choice\n");
scanf_s("%d", &choice);
if (choice == 3)
exit(0);
if (choice >= 1 && choice <= 2)
{
printf("Enter a and b where a + ib is the first complex number.");
printf("\na = ");
scanf_s("%d", &a.real);
printf("b = ");
scanf_s("%d", &a.img);
printf("Enter c and d where c + id is the second complex number.");
printf("\nc = ");
scanf_s("%d", &b.real);
printf("d = ");
scanf_s("%d", &b.img);
}
if (choice == 1)
{
c.real = a.real + b.real;
c.img = a.img + b.img;
if (c.img >= 0)
printf("Sum of two complex numbers = %d + %di", c.real, c.img);
else
printf("Sum of two complex numbers = %d %di", c.real, c.img);
}
else if (choice == 2)
{
c.real = a.real*b.real - a.img*b.img;
c.img = a.img*b.real + a.real*b.img;
if (c.img >= 0)
printf("Multiplication of two complex numbers = %d + %di", c.real, c.img);
else
printf("Multiplication of two complex numbers = %d %di", c.real, c.img);
}
else
printf("Invalid choice.");
printf("\nPress any key to enter choice again...\n");
}
}
基準比較棘手。複雜的算術不是那麼複雜,你可以用'time_t'來測量它需要多長時間,在大多數系統上粒度爲1秒。您將不得不重複計算幾百萬次以使其花費足夠長的時間才能被測量,並且您可能需要使用比time()和time_t更好的度量。至少,使用'clock()'。更可能使用報告爲微秒的'gettimeofday()'或報告爲納秒的'clock_gettime()'。你在哪個平臺上? Windows的答案是不同的。 –
請注意,如果優化程序發現您未使用計算結果,則可能會優化代碼中的計算,因此您將看到運行速度非常快。在不完全抑制優化器的情況下取消優化也是使基準測試變得困難的原因之一。 –
@JonathanLeffler你[不應該使用'gettimeofday'](http://blog.eitanadler.com/2012/11/dont-use-gettimeofday2-or-time3-for.html)要麼(應該有另一個鏈接更有用的替代品,但我現在找不到它)。 – Kninnug