找回密码
 FreeOZ用户注册
查看: 4581|回复: 46
打印 上一主题 下一主题

[经验分享] c# convert string to decimal integer i.e. 100

[复制链接]
跳转到指定楼层
1#
发表于 11-8-2013 09:09:42 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?FreeOZ用户注册

x
本帖最后由 DDD888 于 11-8-2013 08:48 编辑

Good morning,

I am parsing a text file which has some integer string needs to convert to integer. There is around 179891 calls Convert.ToInt32 to convert string to integer and it cost me around 500ms. I thought that I better write a routine myself. Here is my code.

Can anyone make it faster?

    using System;

    public sealed class StringUtility
    {
        public unsafe static int StringConvertToInt(string aLine, int startPostion, int endPosition)
        {
            var result = 0;
            fixed (char* chPtr = aLine)
            {
                var lpszEnd = chPtr + endPosition;
                var lpszPointer = chPtr + startPostion;
                while (lpszPointer < lpszEnd)
                {
                    result *= 10;
                    var value = *lpszPointer;
                    switch (value)
                    {
                        case '0':
                            //result += 0;
                            break;
                        case '1':
                            result += 1;
                            break;
                        case '2':
                            result += 2;
                            break;
                        case '3':
                            result += 3;
                            break;
                        case '4':
                            result += 4;
                            break;
                        case '5':
                            result += 5;
                            break;
                        case '6':
                            result += 6;
                            break;
                        case '7':
                            result += 7;
                            break;
                        case '8':
                            result += 8;
                            break;
                        case '9':
                            result += 9;
                            break;
                        default:
                            throw new Exception("Invalid integer");
                    }
                    lpszPointer++;
                }
            }

            return result;
        }
    }
回复  

使用道具 举报

2#
发表于 11-8-2013 11:00:16 | 只看该作者
switch执行很慢的、result += (x-'0') 会快很多

#include <stdbool.h>
int atoi_(const char* p)
{
  int result = 0;
  bool pos = true;

  if(NULL == str) return 0;
  
  if('-' == *p++)
  {
    pos = false;
  }
  
  while('0' <= *p <= '9')
  {
    result *= 10;
    result += (*p++ - '0')
  }
  
  return pos?result:-result;
}
回复  

使用道具 举报

3#
发表于 12-8-2013 00:14:21 | 只看该作者
奇怪楼主为什么要用C#的指针。

楼上的C++实现应该可以,如果不考虑负数,提供下大概思路吧:

private static char char_0 = '0';
private static char char_9 = '9';

public static int StringToInt(String valueString, int startPosition, in endPosition)
{
    int result = 0;
    char ch;

    for (int i = startPosition; i <= endPosition; i ++)
    {
        ch = valueString[i];
        if (ch < char_0 || ch > char_9)
            return -1;  // Unexpected value: -1 means fail to parse the string

         result = result * 10 + ch - char_0;
    }

    return result;
}
回复  

使用道具 举报

4#
 楼主| 发表于 12-8-2013 09:33:34 | 只看该作者
回复  

使用道具 举报

5#
发表于 12-8-2013 11:59:07 来自手机 | 只看该作者
本帖最后由 michaelsusu 于 12-8-2013 11:17 编辑

Do you know why system conversion is slow? I feel you may find the real bottleneck to avoid re-create your own conversion code blindly. Without knowing the real cause, I do not expect your code can do better than system call.
I doubt the string operation (cut out the digits you want) may compromise your overall performance rather than the conversion itself. If so, you can very likely find a fix by manipulating your current code.
In may cases, such ad hoc code makes the system very hacky and hard to maintain.
回复  

使用道具 举报

6#
发表于 12-8-2013 12:19:44 | 只看该作者
楼上说的有道理,系统代码通常都是最优选择。楼主的实现不大可能提高处理速度,每次转换一组数据都要求Fixed内存,开销太大了。
回复  

使用道具 举报

7#
发表于 12-8-2013 12:30:17 | 只看该作者
michaelsusu 发表于 12-8-2013 09:59
Do you know why system conversion is slow? I feel you may find the real bottleneck to avoid re-creat ...

you're right!
回复  

使用道具 举报

8#
发表于 12-8-2013 12:39:12 | 只看该作者
本帖最后由 ericvan76 于 12-8-2013 10:48 编辑

You should change your code logic to avoid so many conversion calls at one time, which will cause a significant halt and you have to wait, I guess that's the issue you encountered. Instead you can try to distribute them into the run-time logic or loop where they're going to be used.

If you have to do that, you can put something like "loading..." bar or hourglass to tell the operator it's in progress. I don't think you can find a better solution than system conversions, but a hacky code you will get.
回复  

使用道具 举报

9#
发表于 12-8-2013 13:17:03 | 只看该作者
是什么苛刻的环境需要去自己实现字符串数字转换以争取一点点速度的提高?这样的环境就不应该用C#来开发吧?
如果不是什么特殊的环境,还是用系统的比较好。字符串到数字的转换情况不少,比如有些culture下小数点用“,”之类的,一个不小心就会弄错。
回复  

使用道具 举报

10#
 楼主| 发表于 12-8-2013 13:29:50 | 只看该作者
woodheadz 发表于 12-8-2013 12:17
是什么苛刻的环境需要去自己实现字符串数字转换以争取一点点速度的提高?这样的环境就不应该用C#来开发吧? ...

Convert data from csv file to generate file for Microsoft SSIS to run.
回复  

使用道具 举报

11#
发表于 12-8-2013 14:45:37 | 只看该作者
DDD888 发表于 12-8-2013 12:29
Convert data from csv file to generate file for Microsoft SSIS to run.

Why not let SSIS handle the csv file directly?
回复  

使用道具 举报

12#
 楼主| 发表于 12-8-2013 14:47:48 | 只看该作者
本帖最后由 DDD888 于 12-8-2013 13:49 编辑
Mike23 发表于 12-8-2013 13:45
Why not let SSIS handle the csv file directly?


I need geo country location from ip which I am not sure ssis can do the job. And I also add new columns in iis log which means I have to create different package to import the csv if I want to go that way. I am developing my own application to handle the logic, thus the ssis package stays the same.
回复  

使用道具 举报

13#
发表于 12-8-2013 16:39:47 | 只看该作者
DDD888 发表于 12-8-2013 12:29
Convert data from csv file to generate file for Microsoft SSIS to run.

I really don't think it's worthy if you aren't developing an extreme time critical real time system.  Even if the system call does imperilment the converting by array index, your code only get the tiny benefit that comes from replacing p+i with p++.  
回复  

使用道具 举报

14#
发表于 12-8-2013 17:05:14 | 只看该作者
直接用csv以dt_wstr读进去

然后在package里面转会不会更快些?

或者在csv的source里面转?
回复  

使用道具 举报

15#
发表于 12-8-2013 17:13:35 | 只看该作者
本帖最后由 ericvan76 于 12-8-2013 15:16 编辑

我认为lz的问题不是在单个conversion上面,而是他一下子做17万次的conversion,这种情况下自己写conversion根本解决不了问题,如果可以的话,应该对程序逻辑进行优化,避免一次性做那么多次转换,想办法把转换分散到其它地方去。
回复  

使用道具 举报

16#
发表于 12-8-2013 17:25:43 | 只看该作者
本帖最后由 workinvm 于 12-8-2013 16:27 编辑

我测试了一下,Convert.ToIn32 执行100万次用时147ms,楼主代码运行用时是88ms。不过楼主的代码是不完整的,缺少对负数的判断,也缺少对整型溢出的判断。
楼上那个C程序员可能对C#的优化不了解,C#的 switch 在编译后,是以hashtable形式存在于目标代码中的,而不是 C 语言编译器那样编译成 if else 这种形态,所以 switch 并不会带来太大的性能开销。
楼主执行 17万次,就用时500ms,问题显然不在 Convert ,楼主的问题是创建大量的 string 类型对象造成的,因为 CLR在创建 string 对象时不但要在GC为该对象分配内存,而且还要把这个对象的地址和散列值写入到一个全局 hash 表中,以提高string 比较的速度。这个创建开销是很大的。楼主应该考虑将 string 对象分配到堆栈中,或者直接操作char[] 甚至 byte[] 来减少GC 次数。这样才能真正提高性能。

评分

参与人数 1威望 +50 收起 理由
cais + 50 赞直接动手测试!

查看全部评分

回复  

使用道具 举报

17#
发表于 12-8-2013 17:38:21 | 只看该作者
workinvm 发表于 12-8-2013 16:25
我测试了一下,Convert.ToIn32 执行100万次用时147ms,楼主代码运行用时是88ms。不过楼主的代码是不完整的, ...

楼上的方法是用减法来做,应该还是比switch要快一点儿。
回复  

使用道具 举报

18#
发表于 12-8-2013 18:24:38 | 只看该作者
woodheadz 发表于 12-8-2013 16:38
楼上的方法是用减法来做,应该还是比switch要快一点儿。

这些开销和创建 string 的开销根本不在一个数量级,那个减法可能比 switch 稍微快一,两个指令,执行100万次就快那么1-2ms左右。但你创建100万个string要多长时间?估计1秒钟都创建不完。性能优化要抓大放小,不能舍本求末。
回复  

使用道具 举报

19#
发表于 12-8-2013 18:32:47 | 只看该作者
workinvm 发表于 12-8-2013 17:24
这些开销和创建 string 的开销根本不在一个数量级,那个减法可能比 switch 稍微快一,两个指令,执行100万 ...

都已经在讨论自己写代码来转换数字了,已经够舍本逐末了  
既然都在逐末,就逐到底吧。
回复  

使用道具 举报

20#
 楼主| 发表于 12-8-2013 19:14:04 | 只看该作者
workinvm 发表于 12-8-2013 16:25
我测试了一下,Convert.ToIn32 执行100万次用时147ms,楼主代码运行用时是88ms。不过楼主的代码是不完整的, ...

You are right. That is the reason that I directly operate against line with a index and length. I was using split to generate lots of string and call convert.toint32 next.

The operation was eliminated as I don't need to convert to integer any more.
回复  

使用道具 举报

21#
 楼主| 发表于 12-8-2013 21:16:41 | 只看该作者
woodheadz 发表于 12-8-2013 12:17
是什么苛刻的环境需要去自己实现字符串数字转换以争取一点点速度的提高?这样的环境就不应该用C#来开发吧? ...


That is just for fun to see if I can extract some more performance out of the system. It cost me every day 5 seconds to run the conversion and I manage to cut off 1 second. Not a big deal. But if I damaged my database and need to convert three years work, that will make a big difference. I just prepare for the worst happen. Glad for the last three years, such situation only happens four times IIRC.

Anyway if I want to develop in C++ in windows environment, the only reason to do that is just for stopping others to decompile my code. I won't do for performance reason just rewrite in C++ from C#. It is not worth my effort.
回复  

使用道具 举报

22#
发表于 16-8-2013 23:41:25 | 只看该作者
workinvm 发表于 12-8-2013 16:25
我测试了一下,Convert.ToIn32 执行100万次用时147ms,楼主代码运行用时是88ms。不过楼主的代码是不完整的, ...

我也测试了一下,switch和减法的差别不大
不过最要命的是,相比C的库函数来atoi来说,差别太大了。库函数的速度大概是我能用C语言写出来的100倍
估计是硬件上有直接支持了
回复  

使用道具 举报

23#
发表于 20-8-2013 17:58:14 | 只看该作者
cpp10 发表于 16-8-2013 22:41
我也测试了一下,switch和减法的差别不大
不过最要命的是,相比C的库函数来atoi来说,差别太大了。库函数 ...

你是说 C# 的 Convert.ToIn32 比 atoi 慢100倍?也就是说C语言直接调用 atoi 执行100万次只用时1.47毫秒?这个不太可能啊,如果这样,那么 atoi 这个函数只执行了2-3个时钟周期就完成了,也就是说就1-2个指令就结束,这完全不可能,调用函数的压栈和出栈都超过这么多指令了。我怀疑你可能是写的代码被优化了。比如你写 for(int i = 0; i < 1000000; i++) int a = atoi ("1234");
如果你这样写,整个语句会在编译时优化掉,编译器认为这个语句其实什么事情都没干,直接不编译了。你要看汇编到底是怎么写的,才能确定是不是真的快这么多。
回复  

使用道具 举报

24#
发表于 20-8-2013 21:52:15 | 只看该作者
workinvm 发表于 20-8-2013 16:58
你是说 C# 的 Convert.ToIn32 比 atoi 慢100倍?也就是说C语言直接调用 atoi 执行100万次只用时1.47毫秒? ...

我说的是我写的C的实现和C库函数的实现相比,性能差接近100倍。
回复  

使用道具 举报

25#
发表于 21-8-2013 12:17:17 | 只看该作者
cpp10 发表于 20-8-2013 20:52
我说的是我写的C的实现和C库函数的实现相比,性能差接近100倍。

把函数声明改成内联函数试试。编译时打开所有优化选项。
回复  

使用道具 举报

26#
发表于 21-8-2013 16:30:00 | 只看该作者
workinvm 发表于 21-8-2013 11:17
把函数声明改成内联函数试试。编译时打开所有优化选项。


100倍,是不太可能的,如果没有硬件支持
回复  

使用道具 举报

27#
 楼主| 发表于 21-8-2013 17:35:37 | 只看该作者
cpp10 发表于 21-8-2013 15:30
100倍,是不太可能的,如果没有硬件支持

Maybe you post your c code and let me test under visual studio 2013.
回复  

使用道具 举报

28#
发表于 21-8-2013 17:41:31 | 只看该作者
Why don't use Regex to match the numbers. Regex is especially designed and optimized by .NET team, so basically it should be faster than a user's pattern matching code.
回复  

使用道具 举报

29#
发表于 21-8-2013 17:53:25 | 只看该作者
本帖最后由 superopengl 于 21-8-2013 15:56 编辑
workinvm 发表于 12-8-2013 15:25
我测试了一下,Convert.ToIn32 执行100万次用时147ms,楼主代码运行用时是88ms。不过楼主的代码是不完整的, ...


我也看过关于“C#的switch编译后是以hashtable形式存在”的一本书,但我的经验这个说法对于C#来讲是不正确的。两点可以证明
1. 在debug时,可以看到switch的case是从上至下一个一个筛选的,而不是一下子跳到matched case.
2. 从语法设计上,跳出case必须显示break或return,否则会走到下一个case继续运行。如果是用hashtable就没办法走下面的逻辑,如果是hashtable的话,输出“1”后,怎么走到2?Hashtable是做不了的。
switch(k){
   case 1:
      Console.Write("1");
   case 2:
      Console.Write("2");
      break;
}

对于VB.NET的switch,因为是自动跳出case的,所以用hashtable方式实现是有可能的。
回复  

使用道具 举报

30#
 楼主| 发表于 21-8-2013 18:20:01 | 只看该作者
superopengl 发表于 21-8-2013 16:41
Why don't use Regex to match the numbers. Regex is especially designed and optimized by .NET team, s ...

My guess is Regex is very slow compared to my code.
回复  

使用道具 举报

您需要登录后才可以回帖 登录 | FreeOZ用户注册

本版积分规则

小黑屋|手机版|Archiver|FreeOZ论坛

GMT+11, 16-11-2026 13:51 , Processed in 0.064277 second(s), 48 queries , Gzip On, Redis On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表