Thread: How expensive is modulus in a loop?

  1. #1
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534

    How expensive is modulus in a loop?

    Code:
    putchar("rwx"[i % 3]);
    You might recognise that from this FAQ. It is part of a bit of code to list the permission settings on a given file under a *nix type system.

    Now I implemented some code that was not as pretty - it basically was a string of 9 if statements (for the permission bits) which assigned the appropriate char to an array of char. Then I could print the string out when needed.

    As I was mentally comparing these two ways of printing the permission bits of a file, I was wondering how expensive it would be to use modulus like that in a loop. Would it ever make a noticeable difference, or is it something not worth worrying about?

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by kermit View Post
    As I was mentally comparing these two ways of printing the permission bits of a file, I was wondering how expensive it would be to use modulus like that in a loop. Would it ever make a noticeable difference, or is it something not worth worrying about?
    For the loop you're talking about, I wouldn't worry. In general though, a modulus is one of the most expensive integer operations. The answer to your question depends on the complexity of the rest of the code in the loop.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. My loop within loop won't work
    By Ayreon in forum C Programming
    Replies: 3
    Last Post: 03-18-2009, 10:44 AM
  2. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  3. A somewhat bizzare problem!!! - WHILE LOOP
    By bobthebullet990 in forum C Programming
    Replies: 3
    Last Post: 03-31-2006, 07:19 AM
  4. when a while loop will stop ?
    By blue_gene in forum C Programming
    Replies: 13
    Last Post: 04-20-2004, 03:45 PM
  5. using modulus & weighting factors
    By task in forum C Programming
    Replies: 4
    Last Post: 09-11-2002, 05:52 PM