如何减少代码的计算时间? [英] How can I reduce the computational time taken by my code ?

查看:101
本文介绍了如何减少代码的计算时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了这个代码,根据字符的ASCII码找到程序中的字数(每个字的频率),我的程序需要136毫秒来计算整个程序。我正在努力减少这个时间。我可以这样做,因为我是编程新手吗?



我尝试过的事情:



i developed this code that finds the word count(frequency of each word) in the program depending on the character''s ASCII code and my program takes 136 mili seconds to compute the whole program.i am trying to reduce this time.how can i do that since i am new in the programming ?

What I have tried:

#include<iostream>
#include<windows.h>
#include<wchar.h>
#include<conio.h>
#include<string>
#include <ctime>

using namespace std;

int main()
{
	SYSTEMTIME time;
	GetLocalTime(&time);
	wprintf(L"START OF TIME : %02d:%02d:%02d\n", time.wHour, time.wMinute, time.wMilliseconds);
	
	int TOTAL = 0;
	char a[2000];
	cout << "enter the string = ";
	cin.getline(a, 2000);
	int Totalwords = 0;
	int no = 0;

	for (int i = 0; a[i] != ''\0''; i++)
	{

		if ((int(a[i]) >= 65 && int(a[i]) <= 90) || (int(a[i]) >= 97 && int(a[i]) <= 122))
		{

		}
		else
		{
			Totalwords++;
		}
		no = i;
	}

	TOTAL = Totalwords;
	cout << "number of words = " << TOTAL << endl;
	string *words = new string[TOTAL];


	for (int i = 0, j = 0; j < TOTAL, i <= no;)
	{
		if ((int(a[i]) >= 65 && int(a[i]) <= 90) || (int(a[i]) >= 97 && int(a[i]) <= 122))
		{
			words[j] = words[j] + a[i];
			i++;
		}
		else
		{
			j++;
			i++;
		}
	}

	int count = 0;
	for (int i = 0; i< TOTAL; i++)
	{
		bool flag = true;
		for (int j = i - 1; j >= 0; j--)
		{

			if (words[i] == words[j])
			{
				flag = false;
				break;
			}
		}

		if (flag)
		{
			count = 1;
			for (int k = i + 1; k<TOTAL; k++)
			{
				if (words[i] == words[k])
					count++;
			}
			cout << words[i] << " ___ " << count << ''\n'';
		}
	}

	SYSTEMTIME time1;
	GetLocalTime(&time1);
	wprintf(L"END EXECUTION TIME : %02d:%02d:%02d\n", time.wHour, time.wMinute, time.wMilliseconds);
	cout << "Time Difference = " << &time-&time1 << endl;
	_getch();

}

推荐答案

我会用类似于如何实现冒泡排序的循环来编写代码。这是一个例子,包括我在上面评论中提到的经过时间的计时器:

I would code this with loops similar to how a bubble sort is implemented. Here is an example, including the elapsed timer I mentioned in my comment above :
CElapsed timer;
timer.Begin();
int i, j;
int count = 0;
int last = Totalwords - 1;
for( i = 0; i < last; ++i )
{
    for( j = i + 1; j < TotalWords; ++j )
    {
        if( words[i] == words[j] )
            ++count;
    }
}
double elapsed = timer.End();
cout << "elapsed time was " << elapsed << " seconds" << endl;

这是比较的强力方法。如前所述,更好的选择是使用地图。如果您更喜欢蛮力方法,最好将字符串保存在矢量中,这样您就不必关心自己拥有多少字符串,它会自动清理。



我还注意到你有一个重复的代码序列,它接受一行输入并处理它。你应该考虑把它变成一个功能。您可以使用isalpha()来确定字符是字母,还是tchar版本的_istalpha。

This is the brute force method of comparison. A better option would be to use a map, as mentioned previously. If you prefer the brute force method you would be better off saving the strings in a vector so you don''t have to care about how many you have and it will clean up after itself automatically.

I also noticed you have a repeated code sequence that accepts a line of input and processes it. You should consider making that a function. You can use isalpha() to determine if the character is alphabetic, or _istalpha for the tchar version.


Quote:

我没有得到你的问题,对不起。

i didn''t get your question,sorry.



如果你在时间中包含用户输入,时间是没有意义的。

移动开头任何用户输入后的定时,并在定时期间避免输出。


Timing is meaningless if you include user input in the timing.
Move the beginning of timing after any user input, and avoid output during timing.

引用:

如何减少计算时间我的代码采取了什么?

How can I reduce the computational time taken by my code ?



你的代码很简单,但它是以运行时为代价的。

而不是使用数组单词其访问时间与单词数呈线性关系,使用时应使用 map

map - C ++参考 [ ^ ]

std :: map:C ++词典类 - 现代C ++ [ ^ ]



假设你有一个1000字的列表

在一个数组中,要知道一个单词存在,你检查1000个单词。

在地图容器中,单词按字母顺序排序,容器使用树搜索或二分法,这意味着你知道列表中是否只有一个单词只有10个搜索。

因为2 ^ 10 = 1024> 1000



您的算法是:(比如有1000个字)


Your code is simple minded, but it is at expense of running time.
Instead of using the array words which have an access time linear with number of words, use should use a map.
map - C++ Reference[^]
std::map : The C++ dictionary class – Modern C++[^]

Suppose you have a list of 1000 words
In an array, to know if a word exist, you check the 1000 words.
In a map container, the words are sorted alphabetically and the container uses a tree search or dichotomy, this means that you know if a word exist in list with only 10 search.
Because 2^10= 1024 > 1000

Your algorithm is: (say there is 1000 words)

for each input word // 1000 times
  build list of words
for each word in list // 1000 times
  for each previous words // 500000 times
    Check if word already counted // (in previous words)
  if not counted
    for each remaining words // 500000 times in worst case
      count this word // (in remaining words)
    and print word and count



带地图容器的算法:


Algorithm with map container:

for each input word // 1000 times
  copy word in temp variable
  check if word exist
  if not exist
    insert new word in map // 1000 times in worst case
  add 1 to count of that word // 1000 times
for each word in map // 1000 times in worst case
  print word and count


你的主要问题是嵌套。你的循环是嵌套的,因此经常运行。



因为这一行

Your main problem is "nesting". Your loops are nested and so run to often.

Because ot this line
TOTAL = Totalwords;



我会尝试将循环带入此括号


would I try to bring the loops into this braces

else
{
    Totalwords++;
    //here may go the rest of your loops
}

重新考虑这种比较的策略

Rethink the strategy of this comparison

if (words[i] == words[k])

由于大量的比较,它会很慢。你做了两次。那两次不好。



用一些单词制作一些测试数据并使用调试器。

It will be slow because of the mass of comparison. You made it twice. That twice bad.

Make some test data with some words and use the debugger.


这篇关于如何减少代码的计算时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆