如何修改此代码以执行顺序操作 计算挂钟时间的程序 (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");
}
}
答案 0 :(得分:1)
一种典型的方法是记录time()
两次并多次运行代码以获得一阶逼近。
time_t t0,t1;
time(&t0);
int N = 1000000;
for (int i=0; i< N; i++) {
DoCodeUnderTest();
// c.real = a.real + b.real;
// c.img = a.img + b.img;
}
time(&t1);
printf("Time %e\n", (double) (t1-t0) / N);
建议使用分析工具获得更准确的答案。
@Jonathan Leffler建议使用clock()
也是一种改进。
clock_t c1,c12;
c1 = clock();
... // repeat runs of the code
c2 = clock();
printf("Time %e\n", (double) (c1-c0) / CLOCKS_PER_SEC / N);
鉴于1)@Jonathan Leffler关于重复的合法性的第二个建议,因为编译器可能超出代码和2)缓存问题的暗示,这里建议的任何暴力方法充其量只是说明性的而不是确定的时间测量。 / p>