Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Char counting

by dd-b (Monk)
on Dec 08, 2011 at 22:48 UTC ( [id://942509]=perlquestion: print w/replies, xml ) Need Help??

dd-b has asked for the wisdom of the Perl Monks concerning the following question:

How much is it going to cost me (in CPU use) to count the "\n" characters in a string?

I'm getting the string by sysread on a socket into a buffer (not necessarily empty when I start). Somebody else is consuming off the front of the buffer, writing it out another port, so I need to get the line count for the bit I've just read and add that to my running total before I exit.

I'm thinking in terms of looping, using substr, to examine each character; vs. doing something with regexps (it's obvious how to find the first \n in the range, and I can use the length of the match string to tell me where to start searching for the next); vs. using unpack or something to make an array, and grep to find the newlines, and get the count by calling it in a string context.

All of these are sounding a little like too much work to justify for adding a line count to the logging. At the very least, I should check the log level before doing the work. Anyway, I'm wondering how noticeable it'll be. I guess it's just CPU time, which we're not short of (each proxied connection gets its own child process).

Replies are listed 'Best First'.
Re: Char counting
by Eliya (Vicar) on Dec 08, 2011 at 22:54 UTC

    $num = $s =~ tr/\n// counts the newlines and is pretty cheap...

Re: Char counting
by sumeetgrover (Monk) on Dec 09, 2011 at 08:06 UTC

    For each string that you'd run the regular expression to match '\n' character on, it should cost you O(N) in CPU time (for just matching this character), where N is the total number of characters in the string. Then it would cost O(1) each time the counter variable is incremented.

    Note, this CPU time is based on the 'Big O' notation.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://942509]
Approved by ww
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2024-04-25 17:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found